在减去两个日期列 R 时使用 group_by 而不是使用 arrange 时出错

Error while using group_by and not while using arrange when subtracting two date columns R

在下面的数据框中,我试图根据 Col1 确定 Col3 中对应于每个组的最高日期,并从每个组的最高日期中减去 Col2 日期以获得 Col4 中的年份时差:

Data_Frame <- data.frame(Col1 = c("A1", "A1", "A1", "A2", "A2", "A2", "A3", "A3", "A3"), 
                         
                         Col2 = c("2011-03-11", "2014-08-21", "2016-01-17", "2017-06-30", "2018-07-11", "2018-11-28", "2019-09-04", "2020-02-29", "2020-07-12"),
                         
                         Col3 = c("2018-10-22", "2019-05-24", "2020-12-25", "2018-10-12", "2019-09-24", "2020-12-19", "2018-10-22", "2019-06-14", "2020-12-20"))

预期结果是:

这些选项都不会产生结果:

选项 1

Data_Frame <- Data_Frame %>% group_by(Col1) %>% mutate(Col4 = as.numeric(as.POSIXct(max(Data_Frame$Col3)) -  as.POSIXct(Data_Frame$Col2)) / 365.75)

选项 2

Data_Frame <- Data_Frame %>% group_by(Col1) %>% mutate(Col4 = as.numeric(difftime(max(Data_Frame$Col3), Data_Frame$Col2, unit="weeks"))/ 52.25)

我不断收到以下错误:

> Data_Frame <- Data_Frame %>% group_by(Col1) %>% mutate(Col4 = as.numeric(as.POSIXct(max(Data_Frame$Col3)) -  as.POSIXct(Data_Frame$Col2)) / 365.75)
Error: Problem with `mutate()` input `Col4`.
x Input `Col4` can't be recycled to size 3.
i Input `Col4` is `as.numeric(as.POSIXct(max(Data_Frame$Col3)) - as.POSIXct(Data_Frame$Col2))/365.75`.
i Input `Col4` must be size 3 or 1, not 9.
i The error occured in group 1: Col1 = "A1".
Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()
<error/dplyr_error>
Problem with `mutate()` input `Col4`.
x Input `Col4` can't be recycled to size 3.
i Input `Col4` is `as.numeric(as.POSIXct(max(Data_Frame$Col3)) - as.POSIXct(Data_Frame$Col2))/365.75`.
i Input `Col4` must be size 3 or 1, not 9.
i The error occured in group 1: Col1 = "A1".
Backtrace:
  1. dplyr::group_by(., Col1)
  9. dplyr::mutate(...)
 11. dplyr:::mutate_cols(.data, ...)
 12. base::tryCatch(...)
 13. base:::tryCatchList(expr, classes, parentenv, handlers)
 14. base:::tryCatchOne(expr, names, parentenv, handlers[[1L]])
 15. value[[3L]](cond)
 16. dplyr:::stop_mutate_recycle_incompatible_size(e, index = i, dots = dots)
 17. dplyr:::stop_dplyr(...)
Run `rlang::last_trace()` to see the full context.

使用 arrange 而不是 group_by 如下所示,然而,工作:

Data_Frame <- Data_Frame %>% arrange(Col1) %>% mutate(Col4 = as.numeric(as.POSIXct(max(Data_Frame$Col3)) -  as.POSIXct(Data_Frame$Col2)) / 365.75)

Data_Frame <- Data_Frame %>% arrange(Col1) %>% mutate(Col4 = as.numeric(difftime(max(Data_Frame$Col3), Data_Frame$Col2, unit="weeks"))/ 52.25)

我通过 group_by 声明做错了什么,为什么它不起作用?

数据框的结构是:

在 dplyr 函数中,您可以只写 Col2(裸列名称)而不是 Data_Frame$Col2