R获得最大日期字符串

问题描述 投票:0回答:2

我想获得R中最多注明日期的国家/地区

enter image description here

我想获得其最大约会对象的国家/地区作为表格像这样:

enter image description here

r date max
2个回答
0
投票
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))

0
投票
subset(transform(df, date = as.Date(date, "%d.%m.%Y")), date == ave(date, person, FUN = max)) # person country date #2 a germany 2020-05-01 #5 c korea 2023-01-01
© www.soinside.com 2019 - 2024. All rights reserved.