[英]Match values between two columns of two dataframes and create a new column with values of another
I have the 2 dataframes below我有下面的2个数据框
name<-c("Adam","Bill","Jack")
value<-c(3,2,1)
n<-data.frame(name,value)
name value
1 Adam 3
2 Bill 2
3 Jack 1
id<-c("Adam","Adam","Bill","Jack","Jack")
group<-c("A","A","A","B","B")
e<-data.frame(id,group)
id group
1 Adam A
2 Adam A
3 Bill A
4 Jack B
5 Jack B
in which I want to match the values from n$name
and e$id
and then create a new column group
in n
with the respective values found in e$group
like:我想在其中匹配来自n$name
和e$id
的值,然后在n
中创建一个新列group
,其中包含在e$group
中找到的相应值,例如:
name value group
1 Adam 3 A
2 Bill 2 A
3 Jack 1 B
Keep only unique rows of e
and merge
仅保留e
的唯一行并merge
merge(n, unique(e), by.x = 'name', by.y = 'id')
# name value group
#1 Adam 3 A
#2 Bill 2 A
#3 Jack 1 B
With dplyr
:使用dplyr
:
library(dplyr)
n %>% inner_join(distinct(e), by = c('name' = 'id'))
You can use match
:您可以使用match
:
n$group <- e$group[match(n$name, e$id)]
n
# name value group
#1 Adam 3 A
#2 Bill 2 A
#3 Jack 1 B
We can use data.table
我们可以使用data.table
library(data.table)
setDT(n)[unique(e), on = .(name = id)]
# name value group
#1: Adam 3 A
#2: Bill 2 A
#3: Jack 1 B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.