Create new column based on 4 values in another column
You could use nested ifelse
:
col2 <- ifelse(col1==1, "G", ifelse(col1==2, "H", ifelse(col1==3, "J", ifelse(col1==4, "K", NA )))) # all other values map to NA
In this simple case it's overkill, but for more complicated ones...
You have a special case of looking up values where the index are integer numbers 1:4. This means you can use vector indexing to solve your problem in one easy step.
First, create some sample data:
set.seed(1)dat <- data.frame(col1 = sample(1:4, 10, replace = TRUE))
Next, define the lookup values, and use [
subsetting to find the desired results:
values <- c("G", "H", "J", "K")dat$col2 <- values[dat$col1]
The results:
dat col1 col21 2 H2 2 H3 3 J4 4 K5 1 G6 4 K7 4 K8 3 J9 3 J10 1 G
More generally, you can use [
subsetting combined with match
to solve this kind of problem:
index <- c(1, 2, 3, 4)values <- c("G", "H", "J", "K")dat$col2 <- values[match(dat$col1, index)]dat col1 col21 2 H2 2 H3 3 J4 4 K5 1 G6 4 K7 4 K8 3 J9 3 J10 1 G
There are a number of ways of doing this, but here's one.
set.seed(357)mydf <- data.frame(col1 = sample(1:4, 10, replace = TRUE))mydf$col2 <- rep(NA, nrow(mydf))mydf[mydf$col1 == 1, ][, "col2"] <- "A"mydf[mydf$col1 == 2, ][, "col2"] <- "B"mydf[mydf$col1 == 3, ][, "col2"] <- "C"mydf[mydf$col1 == 4, ][, "col2"] <- "D" col1 col21 1 A2 1 A3 2 B4 1 A5 3 C6 2 B7 4 D8 3 C9 4 D10 4 D
Here's one using car
's recode
.
library(car)mydf$col3 <- recode(mydf$col1, "1" = 'A', "2" = 'B', "3" = 'C', "4" = 'D')
One more from this question:
mydf$col4 <- c("A", "B", "C", "D")[mydf$col1]