ybcha204
ybcha204

Reputation: 91

How do I assign one value to multiple factor levels at once in R?

I have a data frame with two columns, last name and a new column where I want to assign "Yes" or "No".

df <- data.frame(x <- as.factor(c("a","b","c","d","e")), y <- NA)
colnames(df)<-c("last name", "newCol")

Let's say I want to assign "No" in newCol for "a", "c", "e". How do I assign "No" to all three factor levels at once?

I tried using the logical operator, |, with the factor levels, but it did not work. I have been able to do it by assigning "No" to individual levels, but I find it inefficient.

Upvotes: 0

Views: 859

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50678

You can use %in% to check for "a", "c", "e" in one step:

df$newCol[df$`last name` %in% c("a", "c", "e")] <- "No"
df;
#last name newCol
#1         a     No
#2         b   <NA>
#3         c     No
#4         d   <NA>
#5         e     No

Or using a tidyverse approach using ifelse:

require(tidyverse);
df %>% mutate(newCol = ifelse(`last name` %in% c("a", "c", "e"), "No", "NA"))
#  last name newCol
#1         a     No
#2         b     NA
#3         c     No
#4         d     NA
#5         e     No

or slightly different using replace:

df %>% mutate(newCol = replace(newCol, `last name` %in% c("a", "c", "e"), "No"))

Upvotes: 3

Related Questions