R获取最大日期字符串
我想得到R中最多约会的人的国家 我想把他最大约会对象的国家作为表格 就像这样:R获取最大日期字符串,r,date,max,R,Date,Max,我想得到R中最多约会的人的国家 我想把他最大约会对象的国家作为表格 就像这样: 这里有一个选项。按“人员”分组后,将“日期”转换为具有lubridate的date类(假设“日期”格式为%d.%m.%Y),获取具有which.max和slice的行的索引 library(dplyr) library(lubridate) df1 %>% group_by(person) %>% slice(which.max(dmy(date))) # if the format
这里有一个选项。按“人员”分组后,将“日期”转换为具有
lubridate
的date
类(假设“日期”格式为%d.%m.%Y
),获取具有which.max
和slice
的行的索引
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
数据
df1在base R中,我们可以首先将
转换为日期
对象,然后为每个人
选择最大日期
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
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))
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