简体   繁体   中英

How can I check in R using dplyr the values of a vector if they correspond (exist) to a column of a data frame?

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 ?

你可以使用 %in%

df %>% mutate(condition = var1 %in% var2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM