Let's say I have a data frame in R that looks like this :
var1 | lc |
---|---|
A | london |
B | athens |
C | amsterdam |
D | new york |
E | tokyo |
F | barcelona |
G | rome |
H | mexico city |
I | cairo |
var1 = c("A","B","C","D","E","F","G","H","I")
lc = c("london","athens","amsterdam","new york","tokyo","barcelona","rome","mexico city","cairo")
df = tibble(var1,lc);df
Now I have a vector of interest that contains some values that I have to check.
var2 = c("A","C","E","F","G","H","I","J","K","L","M")
My condition of interest is that if the elements of the column vector var1 exist in the second vector (var2).
Ideally a want to mutate (dplyr phrase) a new column that will contain the output if this logical condition and must look like this.
var1 | lc | condition |
---|---|---|
A | London | TRUE |
B | athens | FALSE |
C | amsterdam | TRUE |
D | new york | FALSE |
E | tokyo | TRUE |
F | barcelona | TRUE |
G | rome | TRUE |
H | mexico city | TRUE |
I | cairo | TRUE |
How can I do it in R using dplyr ? Any help ?
CodePudding user response:
You could use %in%
df %>% mutate(condition = var1 %in% var2)