首页 > 解决方案 > R获取最大日期字符串

问题描述

我想在 R 中获得最大日期的人国家

在此处输入图像描述

我想得到他最大日期的人的国家,像这样的表格:

在此处输入图像描述

标签: rdatemax

解决方案


这是一种选择。按'person'分组后,将'date'转换为Dateclass with lubridate(假设'date'格式为in %d.%m.%Y),得到行withwhich.maxslice该行的索引

library(dplyr)
library(lubridate)
df1 %>%
   group_by(person) %>%
   slice(which.max(dmy(date)))
   # if the format is %m.%d.%Y"
   # slice(which.max(mdy(date)))
# A tibble: 2 x 3
# Groups:   person [2]
#  person country date      
#  <chr>  <chr>   <chr>     
#1 a      germany 01.05.2020
#2 c      korea   01.01.2023

或使用data.table

library(data.table)
setDT(df1)[, .SD[which.max(as.IDate(date, "%d.%m.%Y"))], person]

数据

df1 <- structure(list(person = c("a", "a", "c", "c", "c"), country = c("usa", 
"germany", "france", "china", "korea"), date = c("01.01.2020", 
"01.05.2020", "01.01.2021", "01.01.2022", "01.01.2023")),
class = "data.frame", row.names = c(NA, 
-5L))

推荐阅读