如何对R语言DataFrame中相同月份的行值进行求和计算
按月份对DataFrame的Values列求和
我有一个包含日期列的简化DataFrame,对应的R代码如下:
Date = c("2011-01-01", "2011-02-01", "2012-01-01", "2012-02-01", "2013-01-01", "2013-02-01") Values = c(1.123389e+02, 7.975111e+01, 7.782333e+01, 4.643222e+01, 2.625444e+01, 8.565556e+00) df <- data.frame(Date, Values) df <- df %>% dplyr::mutate(Date = as.Date(as.character(Date), format = "%Y-%m-%d"));
该DataFrame的数据如下:
| Date | Values |
|---|---|
| 2011-01-01 | 112.3389 |
| 2011-02-01 | 79.75111 |
| 2012-01-01 | 77.82333 |
| 2012-02-01 | 46.43222 |
| 2013-01-01 | 26.25444 |
| 2013-02-01 | 8.565556 |
需要将相同月份对应的Values值求和,得到如下结果:
| Date | Sum |
|---|---|
| Jan | 216.4167 |
| Feb | 134.7489 |
解决方案
方法1:使用dplyr + lubridate(简洁直观)
借助lubridate的month()函数快速提取月份缩写,结合dplyr完成分组求和:
# 首次使用需安装依赖包 install.packages(c("dplyr", "lubridate")) library(dplyr) library(lubridate) result <- df %>% mutate(Month = month(Date, label = TRUE, abbr = TRUE)) %>% group_by(Month) %>% summarise(Sum = round(sum(Values), 4)) %>% rename(Date = Month) print(result)
方法2:仅用dplyr + 基础R(无额外依赖)
如果不想安装lubridate,可以用基础R的format()函数提取月份缩写:
library(dplyr) result <- df %>% mutate(Month = format(Date, "%b")) %>% group_by(Month) %>% summarise(Sum = round(sum(Values), 4)) %>% rename(Date = Month) print(result)
两种方法都会输出符合需求的结果:
# A tibble: 2 × 2 Date Sum <chr> <dbl> 1 Jan 216.4 2 Feb 134.7
内容的提问来源于stack exchange,提问作者ΚΩΝΣΤΑΝΤΙΝΟΣ ΠΑΝΑΓΙΩΤΟΥ
相关产品推荐
相关产品推荐

