Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

You could use %in%

df %>% mutate(condition = var1 %in% var2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading