简体   繁体   中英

removing rows based on matching values in r dataframe

I currently have a dataframe full of IDs, and a different dataframe with IDs and other values, such as:

df1:        ID           df2:         ID      X1      
            1                          1       12
            3                          2       23
            4                          3       22
            6                          4       11
            7                          5       66
            8                          6       17

I am looking to remove rows in df2, if their ID does not appear in df1. There are fewer rows in df1, I'm not sure if this impacts the code at all!

Any help would be greatly appreciated. Thank you.

Simply use:

df2[df2$ID %in% df1$ID,]

By the way, creating reproducible examples is very importand on SO.

You could include the below into your question by editing it

ID <- letters[1:5]
X1 <- 5:1
df1 <- data.frame(ID[1:3])
df2 <- data.frame(ID, X1)

People would then be able to show you results of their answers based on real, if primitive, data

> df2[df2$ID %in% df1$ID,]
  ID X1
1  a  5
2  b  4
3  c  3

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