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 to filter a dataframe using a preset vector in R

In the dataframe below, I want to filter column code using a preset vector x

# dataframe
set.seed(123)
code <- c(5001,5001,5250,5250,5425,5425,5610,5610,5910,5910)
state <- c("PA","PA","DE","DE","NY","NY","NJ","NJ","CO","CO")
rev_1990 <- runif(10, min=1000000, max=10000000000)
rev_1991 <- runif(10, min=1000000, max=10000000000)
rev_1992 <- runif(10, min=1000000, max=10000000000)

df <- data.frame(code, state, rev_1990,rev_1991,rev_1992)
df

# preset vector
x <- c(5250,5610,5910)
x

My attempt returns only unique rows of x, I want to return all rows containing x

library(dplyr)

df%>% 
  filter(code == x) # this returns 3 rows instead of 6 rows

Thanks for your attempt

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

>Solution :

Use %in%:

df %>% 
  filter(code %in% x)
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