在R语言中如何将日度转年度数据?批量用last()替代逐变量summarise
在R语言中将日度数据转换为年度数据(批量使用
last()聚合) 步骤1:准备并检查数据
首先确保你的数据集包含日期类型的列,以下是示例日度数据集:
library(tidyverse) # 生成2020-2022年的日度模拟数据 set.seed(123) daily_data <- tibble( date = seq(as.Date("2020-01-01"), as.Date("2022-12-31"), by = "day"), sales = rnorm(length(date), mean = 100, sd = 10), inventory = runif(length(date), min = 50, max = 200), customers = sample(30:80, length(date), replace = TRUE) )
步骤2:批量转换为年度数据
通过group_by按年份分组后,使用across()函数一次性对所有变量应用last(),无需逐个列调用summarise:
annual_data <- daily_data %>% # 从日期列提取年份作为分组依据(需lubridate包,或用format(date, "%Y")) mutate(year = lubridate::year(date)) %>% group_by(year) %>% # 对所有列批量应用last(),取年度最后一条记录 summarise(across(everything(), last()), .groups = "drop")
关键细节说明
lubridate::year(date):快速从日期中提取年份,若未安装lubridate,可替换为year = as.integer(format(date, "%Y"))。across(everything(), last()):everything()表示选中所有列,across()批量对每列执行last(),直接获取年度最后一条数据。.groups = "drop":分组完成后自动取消分组状态,避免后续操作的分组警告。
可选:指定目标列
如果不需要对所有列应用last(),可精准选择列(比如仅数值型列):
annual_data_numeric <- daily_data %>% mutate(year = lubridate::year(date)) %>% group_by(year) %>% summarise(across(where(is.numeric), last()), .groups = "drop")
内容的提问来源于stack exchange,提问作者user19107602
相关产品推荐
相关产品推荐

