使用其他数据框中的值保留行

时间:2018-05-19 19:27:41

标签: r

这是第一个数据帧:

  df1 <- data.frame(pid = c(12,13,14,15,16,17,32,44,3,4,59,2,91), name = c(product1,product2,product3,product,product4,product5,product6,product7,product8,product9,product10,product11,product12,product43))

我想使用df2的pid作为索引值来提取df1的新子集:

df2 <- data.frame(pid = c(12,13,14,4,2))

子集示例:

  df1 <- data.frame(pid = c(12,13,14,15,16,17,32,44,2,4,59,2,91), name = c(product1,product2,product3,product10,product12))

我怎么能做到?

1 个答案:

答案 0 :(得分:1)

不确定您需要什么,因为子集数据帧的示例无效。但是,这可能是您正在寻找的解决方案:

df1 <- data.frame(pid = c(12,13,14,15,16,17,32,44,3,4,59,2,91), 
                 name = c("product1","product2","product3","product4",
                 "product5","product6","product7","product8","product9",
                 "product10","product11","product12","product43"))
df2 <- data.frame(pid = c(12,13,14,4,2))

require(dplyr)
right_join(df1,df2)

结果:

  >right_join(df1,df2)
  Joining, by = "pid"

  pid      name
1  12  product1
2  13  product2
3  14  product3
4   4 product10
5   2 product12