简化示例,示例数据:
data_f <- data.frame(id=rep(1:10),cat=rep("non",10),nam=paste(rep(1:10),rep(1:10),letters[1:10],sep=""))
data_f[,2] <- c("one","","","two","","tree","","four","","")
data_d <- data.frame(nam1=paste(rep(1:10),rep(1:10),letters[1:10],sep=""))
期望的结果:
nam1 new.name
1 11 a one
2 22 b one
3 33 c one
4 44 d two
5 55 e two
6 66 f tree
7 77 g tree
8 88 h four
9 99 i four
10 1010 j four
单词:如果列nam
的任何条目与nam1
中的data_d
匹配,则从cat
获取该类别的data_f
列将它放在nam1
的相应值旁边。请注意,nam1
和nam
的条目随机分散,不按示例顺序排列。
我未能找到有效的解决方案。
答案 0 :(得分:1)
这是一种可能性:
merge(data_d,
transform(data_f[-1], cat = ave(cat, cumsum(cat != ""), FUN = function(x) x[1])),
by.x = "nam1", by.y = "nam", sort = FALSE)
结果:
nam1 cat
1 11a one
2 22b one
3 33c one
4 44d two
5 55e two
6 66f tree
7 77g tree
8 88h four
9 99i four
10 1010j four