我试图从一列中的一组日期中获得最小和最大值。当我运行下面的代码时,我在查找最小值时得到了第一个条目的最大日期(其余的都是ok的),在查找最大值时得到了第一个条目的最大条目的最小日期(其余的都是ok的)。
数据:
structure(list(PR.Number = structure(c(1L, 1L, 2L, 2L, 3L, 3L
), .Label = c("PR1234", "PR1235", "PR1236", "PR1237", "PR1238"
), class = "factor"), Date.received = structure(c(2L, 1L, 7L,
10L, 8L, 9L), .Label = c("01/02/2024", "05/01/2022", "09/09/2023",
"09/09/2025", "10/03/2023", "10/03/2024", "15/07/2022", "16/11/2022",
"16/11/2023", "30/09/2022"), class = "factor")), row.names = c(NA,
6L), class = "data.frame")
代码马克斯:
R_Date.Test %>%
group_by(PR.Number) %>%
slice_max(Date.received)
代码分钟:
R_Date.Test %>%
group_by(PR.Number) %>%
slice_min(Date.received)
最小输出:PR.Number Date.received
1 PR1234 01/02/2024 2 PR1235 15/07/2022
3 PR1236 16/11/2022
4 PR1237 10/03/2023
5 PR1237 10/03/2023
6 PR1238 09/09/2023
Max输出:PR.Number Date.received
1 PR1234 05/01/2022 2 PR1235 30/09/2022
3 PR1236 16/11/2023
4 PR1237 10/03/2024
5 PR1238 09/09/2025
您的Date.received
是一个因子而不是Date对象所以试试:
R_Date.Test$Date.received <- as.Date(df$Date.received , "%d/%m/%Y")
# then apply your code above
R_Date.Test %>%
group_by(PR.Number) %>%
slice_min(Date.received)