I've got a vector of characters, which looks like this:
> head(vc)
[1] "0012" "100" "1001" "1003" "1005" "107"
I also have a dataframe, which looks like this:
code city
0012 ty
987 ch
1005 ny
111 al
I want to add a column to my dataframe, where, if a given code
is found in vc
, then the column will say 'yes', and if it is not, it will say 'no'. Something like this:
code city viable
0012 ty yes
987 ch no
1005 ny yes
111 al no
Also, the datasets are big ( 1million rows), so I need an efficient way of doing this matching.
CodePudding user response:
It will be something like this.
(If you provide a dput
of data I could be sure but this is a freestyle answer)
df['viable'] <- ifelse(df$code %in% vc,"yes","no")
CodePudding user response:
I would aim at putting the information in your data.frame. Try
library(dplyr)
df <- data.frame(code = c(0012,987,1005,111), city = c("ty","ch","ny","al"))
df %>% mutate(variable = if_else(city %in% c("ty", "ny"), "yes", "no"))
For more complex conditions you may use case_when()