您好我有2个数据框:
d <- data.frame(v1 = c("A","B","C","D","E","F","G","H"),
v2 = c(1,2,3,4,5,6,7,8),
v3 = c(1,2,3,4,5,6,7,8)) )
m<-data.frame(v4 = c("B","H","A","C","D"))
我希望以m
与m$v4
匹配的方式更改d$v1
,并创建m$v5
,其相对数据为d$v2
根据匹配情况,m$v6
的相对数据为d$v3
。
我的最终m
数据框应如下所示:
m
v4 v5 v6
1 B 2 2
2 H 8 8
3 A 1 1
4 C 3 3
5 D 4 4
答案 0 :(得分:2)
有很多方法可以做到这一点:
使用dplyr::left_join
:
dplyr::left_join(m, d, by = c("v3" = "v1"))
# v3 v2
#1 B 2
#2 H 8
#3 A 1
#4 C 3
#5 D 4
使用merge
:
merge(m, d, by.x = "v3", by.y = "v1", sort = F)
# v3 v2
#1 B 2
#2 H 8
#3 A 1
#4 C 3
#5 D 4
与修订后的样本数据类似
merge(m, d, by.x = "v4", by.y = "v1", sort = F)
# v4 v2 v3
#1 B 2 2
#2 H 8 8
#3 A 1 1
#4 C 3 3
#5 D 4 4
答案 1 :(得分:0)
我们可以使用match
base R
m$v4 <- d$v2[match(m$v3, d$v1)]
如果我们有多个列,那么遍历感兴趣的列并执行match
m[paste0("v", 5:6)] <- lapply(d[-1], function(x) x[match(m$v4, d$v1)])
m
# v4 v5 v6
#1 B 2 2
#2 H 8 8
#3 A 1 1
#4 C 3 3
#5 D 4 4