在我最终-7像Two by two matching between dataframes in r这样做之前,请允许我说我已经阅读了以下页面:
实际上,最后一个与我想要的非常相似,但不一样,因为我的专栏不同
我有两个数据帧,比方说:
> d <- data.frame(year=c(2004,2004,2006),month = c(1,5,3), height = c(1000,2000,3000) )
> d
year month height
1 2004 1 1000
2 2004 5 2000
3 2006 3 3000
> e <- data.frame(year=c(2004),month=c(5), height = c(9999))
> e
year month height
1 2004 5 9999
显然,真实数据比这长。
我想将e中的值合并到d
中尝试原始合并:
> merge(d,e)
[1] year month height
<0 rows> (or 0-length row.names)
确定。所以添加“by”:
> merge(d,e,by=c("year","month"))
year month height.x height.y
1 2004 5 2000 9999
好吧,它做了一个内部联接,并删除了d中的所有原始数据。所以尝试左外连接:
> merge(d,e,by=c("year","month"),all.x = T)
year month height.x height.y
1 2004 1 1000 NA
2 2004 5 2000 9999
3 2006 3 3000 NA
它进行了连接,并且根据外连接定义它是正确的,但它没有做我想要的,即从e中的值更新d中的值。我真正想要的更像是一个sql更新:
for (year,month,height) in e:
update d set d.height=e.height where d.year = e.year and d.month = e.month
即我想要的结果是:
> magic(d,e)
year month height
1 2004 1 1000
2 2004 5 9999
3 2006 3 3000
当然,我可以写一堆for
循环,但是我希望有一些矢量化方法可以做到这一点?
编辑:我的示例只有一个键列,但我的真正问题有两个。更新了示例以反映这一点。
答案 0 :(得分:7)
您可以使用data.table
library(data.table)
DD <- as.data.table(d)
DE <- as.data.table(e)
setkey(DD, year, month)
setkey(DE, year, month)
DD[DE, height := i.height]
请注意,我的前缀高度为i.
,以确保它正在从i
组件中读取高度值。
如果你阅读了data.table插图的介绍,你将很快理解rownames和data.table键之间的关系!
答案 1 :(得分:2)
实际上,以下方法更直接:
rownames( d ) <- d$id
d[ e$id, ]$height <- e$height
更新:由于您的密钥实际上是“年月”,因此您可能最好使用数据表,但如果您不愿意使用它,那么您可以执行以下操作:
rownames( d ) <- paste( d$year, d$month )
d[ paste( e$year, e$month ), ]$height <- e$height