【发布时间】:2021-11-23 18:11:33
【问题描述】:
我想通过 df1$plots = df2$plots 和最近的日期对两个 data.frames 进行左连接。 两个 data.frames 的一些绘图编号也会重复,就像在这个例子中一样:
df1=data.frame(plots=c(1,2,3,4,1),dates=as.POSIXct(c('01.01.2021','01.02.2021','01.03.2021','01.04.2021','02.01.2021'),format='%d.%m.%Y'))
df1
plots dates
1 1 2021-01-01
2 2 2021-02-01
3 3 2021-03-01
4 4 2021-04-01
5 1 2021-01-02
df2=data.frame(plots=c(1,2,3,4,1,2,3,4),dates=as.POSIXct(c('05.01.2021','02.02.2021','01.01.2021','29.03.2021','31.12.2020','17.06.2021','05.03.2021','08.02.2021'),format='%d.%m.%Y'),TargetValues=c(100:107) )
df2
plots dates TargetValues
1 1 2021-01-05 100
2 2 2021-02-02 101
3 3 2021-01-01 102
4 4 2021-03-29 103
5 1 2020-12-31 104
6 2 2021-06-17 105
7 3 2021-03-05 106
8 4 2021-02-08 107
我希望 df1 最终看起来像这样:
plots dates Values
1 1 2021-01-01 104
2 2 2021-02-01 101
3 3 2021-03-01 106
4 4 2021-04-01 103
5 1 2021-01-02 104
这是我尝试过的:
df1.2 <- lapply(intersect(df1$plots,df2$plots,function(id) {
d1 <- subset(df1,plots==id)
d2 <- subset(df2,plots==id)
d1$indices <- sapply(d1$date,function(d) which.min(abs(d2$date - d)))
d2$indices <- 1:nrow(d2)
merge(d1,d2,by=c('plots','indices'))
}))
但我收到一条错误消息“match.fun(FUN) 中的错误:缺少参数“FUN”,没有默认值”。
我该如何修复代码,或者有人对如何完成任务有不同的想法?
【问题讨论】: