Question

So one of the problems I am stuck on is that:

I have some variable X which takes values {1,2,3,4}. Thus

X: 1 2 2 4 2 3

What I want to do, is turn the 1's and 2's into A, and the 3's and 4's into B.

Is there any possible suggestions how I would go about doing this. Or hints?

I was initially thinking of using the subset command, but these seems to just extract them from the dataset.

Was it helpful?

Solution

X <- c(1,2,2,4,2,3)
Y <- ifelse(X %in% 1:2, "A", "B")
## or
Y <- cut(X,breaks=c(0,2.5,5),labels=c("A","B"))

The latter approach creates a factor rather than a character vector; you can use as.character to turn it back into a character vector if you want.

OTHER TIPS

One possible option is to use recodeVar from the doBy package

library(doBy)
x <- c(1, 2, 2, 4, 2, 3)
src = list(c(1, 2), c(3, 4))
tgt = list("A", "B")
recodeVar(x, src, tgt)

which yields

> recodeVar(x, src, tgt)
[1] "A" "A" "A" "B" "A" "B"
> 

Or you can use the car package:

library(car)
recode(x, "1:2='A'; 3:4='B'")

Another alternative:

LETTERS[ceiling((1:4)/2)]
[1] "A" "A" "B" "B"

LETTERS[ceiling(X/2)]
[1] "A" "A" "A" "B" "A" "B"

if it's dataframe, dplyr package:

dataframe %>%
  mutate (newvar = case_when(var %in% c(1, 2) ~ "A",
                   case_when(var %in% c(3, 4) ~ "B")) -> dataframe
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top