I have a data frame in which I'd like to make a new column which is set to TRUE
or FALSE
depending on whether it matches with a vector.
So far I've tried two different approaches, the first directly using the %in%
operator to check whether elements of test
occurred in column apples
, the second by putting this in an ifelse
statement.
test <- c("a","b","c")
df <- tibble(apples = c("a","d","e","f","z","g","c"))
#First attempt
df_match <- df %>%
mutate(
match = test %in% apples
)
#Second attempt
df_match <- df %>%
mutate(
match = ifelse(test %in% apples,TRUE,FALSE)
)
The desired output for column 'match' would be
> df$match
[1] TRUE FALSE FALSE FALSE FALSE FALSE TRUE
CodePudding user response:
Using base R
transform(df, match = apples %in% test)