You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用dplyr包计算数据框特定列中两个行范围的平均值?

使用dplyr计算指定月份区间的调查数量平均值

可以通过添加分组标识 + 分组聚合的方式快速实现需求,具体代码如下:

# 加载dplyr包
library(dplyr)

# 示例数据框
month = c(1,2,3,4,5,6,7,8,9,10,11,12)
surveys = c(4,5,3,7,3,4,4,4,6,1,1,7)
df = data.frame(month, surveys)

# 计算目标平均值
df %>%
  # 添加分组标签:区分5-8月和其他月份
  mutate(period = case_when(
    month %in% 5:8 ~ "5-8月",
    TRUE ~ "其余月份"
  )) %>%
  # 按分组标签聚合,计算平均值
  group_by(period) %>%
  summarise(平均调查数量 = mean(surveys))

代码说明:

  • mutate() + case_when():创建新列period,标记每行数据所属的区间(5-8月/其余月份)
  • group_by(period):按照分组列对数据进行分组
  • summarise():对每个分组计算调查数量的平均值,最终返回包含分组标签和对应平均值的汇总表

运行后会得到如下结果:

# A tibble: 2 × 2
  period   平均调查数量
  <chr>          <dbl>
1 5-8月            3.75
2 其余月份          4.125

内容的提问来源于stack exchange,提问作者Rnoobie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:55:21