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

基于DPLYR实现按月累计会员数统计 无需For循环的Tidy风格实现方案

实现方案

使用dplyr搭配purrr即可实现完全符合tidy风格的代码,替代原有for循环:

  1. 首先加载依赖包
library(dplyr)
library(purrr)
  1. 核心实现代码
total.membership <- map_dfr(month.list, ~ {
  total.membership.working %>%
    ungroup() %>%
    filter(Month <= .x) %>%
    summarise(
      Month = max(Month),
      total_membership = n_distinct(`Mem Account`)
    )
})

上述代码逻辑和原有for循环完全一致,通过map_dfr遍历month.list中的每一个日期阈值,自动将每次计算得到的单行统计结果按遍历顺序拼接为最终数据框,无需手动循环绑定行。如果需要最终结果按月份升序排列,可以在末尾补充排序逻辑:

total.membership <- total.membership %>% arrange(Month)

内容的提问来源于stack exchange,提问作者Jeremy R. Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 11:27:01