match row names of two data frames and subset only matching rows in R

Viewed 529

I would like to subset "z" data frame based on rows from "b" data frame

>z
    Fox Prox Sox
ABC 1   2    3
DEF 1   1    0
GHI 1   0    2
ABD 1   3    0
AAB 2   3    2

>b
ABC 1
DEF 7
ABD 1

>output
   Fox Prox Sox
ABC 1   2    3
DEF 1   1    0
AAD 2   3    2
2 Answers

You can directly use the rownames from b to subset z.

z[rownames(b),] 
#    Fox Prox Sox
#ABC   1    2   3
#DEF   1    1   0
#ABD   1    3   0

I believe the merge function is what you need:

newdf <- merge(z, b, by =letters)

or else I think you can do this dplyr

library(dplyr)

z <- z %>%
  filter(letters %in% b$letters)

I put "letters" as the name of the first column. Because I didn't see a column name. You might first have to do this:

colnames(z) <- c("letters", "Fox", "Prox", "Sox")
Related