【问题标题】:R merging data based on nearest date and under fulfilled conditionR基于最近的日期并在满足条件下合并数据
【发布时间】: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”,没有默认值”。

我该如何修复代码,或者有人对如何完成任务有不同的想法?

【问题讨论】:

    标签: r date join merge


    【解决方案1】:

    您可以通过plots 连接两个数据框,并为每个图值和日期选择绝对差值最小的行。

    library(dplyr)
    
    left_join(df1, df2, by = 'plots') %>%
      group_by(plots, dates.x) %>%
      slice(which.min(abs(dates.x - dates.y))) %>%
      ungroup %>%
      select(plots, dates = dates.x, TargetValues)
    
    #  plots dates               TargetValues
    #  <dbl> <dttm>                     <int>
    #1     1 2021-01-01 00:00:00          104
    #2     1 2021-01-02 00:00:00          104
    #3     2 2021-02-01 00:00:00          101
    #4     3 2021-03-01 00:00:00          106
    #5     4 2021-04-01 00:00:00          103
    

    【讨论】:

    • 谢谢!在我这样做之后,我的目标数据帧的行数从 292 减少到 177。你知道为什么以及如何解决这个问题吗?编辑:我把最后的 select (...) 改成了 select_all,因为我想查看所有行中的所有数据
    • df1plotsdates 列中有 NA 吗?此外,如果您同时删除 select 语句,它将选择所有列。
    • 是的,NAs 中有 plots。我删除了 select 语句并以ungroup 结尾,但行数仍在减少。当NAs 出现时,我可以跳过吗?
    • 减少发生在slice() 参数之后
    猜你喜欢
    • 2022-01-03
    • 2018-08-15
    • 2017-08-26
    • 2016-10-06
    • 1970-01-01
    • 2020-12-24
    • 2016-08-31
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多