R语言 我想计算一下离下次会议还有多少天

xfb7svmp  于 2023-09-27  发布在  其他
关注(0)|答案(2)|浏览(88)

我想计算的天数,以下次会议作为样本。

meetings=c("2023-06-21","2023-05-03","2023-03-22","2023-02-01","2022-12-07")
  

dates=c("2023-08-01","2023-04-01","2023-03-01","2023-02-01","2023-01-01")

还这个

c(NA,32,21,0,31)

我已经尝试过了,但并不认为所有的会议

as.Date(meetings)-as.Date(dates)
Time differences in days
[1] -41  32  21   0 -25
ryoqjall

ryoqjall1#

迄今为止的第一个转换是as.Date。对日期进行排序,然后使用sapply,定义next_meeting后使用difftime

meetings <- as.Date(c("2023-06-21", "2023-05-03", "2023-03-22", "2023-02-01", "2022-12-07"))
dates <- as.Date(c("2023-08-01", "2023-04-01", "2023-03-01", "2023-02-01", "2023-01-01"))

meetings <- sort(meetings)

sapply(dates, function(date) {
  next_meeting <- meetings[which(meetings >= date)][1]
  if (is.na(next_meeting)) {
    return(NA)
  } else {
    return(as.integer(difftime(next_meeting, date, units = "days")))
  }
})

产出:

[1] NA 32 21  0 31
nom7f22z

nom7f22z2#

这也可以在dplyr 1.1.0+中使用join_byclosest来完成:

left_join(data.frame(dates = as.Date(dates)),
          data.frame(meetings = as.Date(meetings)),
          join_by(closest(dates <= meetings))) |>
  mutate(next_meeting = as.numeric(meetings - dates))


       dates   meetings next_meeting
1 2023-08-01       <NA>           NA
2 2023-04-01 2023-05-03           32
3 2023-03-01 2023-03-22           21
4 2023-02-01 2023-02-01            0
5 2023-01-01 2023-02-01           31

相关问题