如何使用R在两个数据帧中匹配列的基础上提取所有值?

时间:2018-01-10 13:31:15

标签: r dataframe match lookup

我有一个像这样的数据框n

id subject 
-------------
1  discount less

2  product good

3  product good

4  wonderful service

5  discount less

另一个数据框说像这样

Subject   Rate
----------------
product good  20

wonderful service 30

discount less  10

i want the output as :

id   subject  rate
--------------------
1,5   discount less

2,3   product good

4    wonderful service

如果我像p$id <- n$id[match(p$subject,n$subject)]那样匹配,则只会显示匹配的第一个元素...但我想要所有的ID ....

任何人都可以指导我这个

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

n$subject<-as.character(n$subject)
id=sapply(unique(n$subject),function(x) paste(as.character(n[n$subject==x,]$id), collapse=", "))
subject=unique(n$subject)
df1=data.frame(id=id,subject=subject)
df2=merge(df1,p,by="subject")
df2=df2[c("id", "subject", "Rate")]