基于用户输入的R语言filter-mutate分组求和问题求助
问题:基于动态分组条件实现按组求和失败
需求背景
我希望通过用户输入或全局变量实现数据的筛选-突变处理,核心逻辑是用筛选编号指定分组条件,对目标dataframe分组后执行对应的突变操作。
已定义的分组条件列表
先定义了以下分组条件,并将其存入列表以便通过编号调用:
# 各分组条件定义 ymsd <- c("year", "month", "site", "depth") # 按年、月、站点、深度分组 ymsdc <- c("year", "month", "site", "depth", "ncore") # 按年、月、站点、深度、芯号分组 ymsdt <- c("year", "month", "site", "depth", "sample") # 按年、月、站点、深度、样本类型分组 ymsdct <- c("year", "month", "site", "depth", "ncore", "sample") # 按年、月、站点、深度、芯号、样本类型分组 yms <- c("year", "month", "site") # 按年、月、站点分组 ym <- c("year", "month") # 按年、月分组 s <- c("site") # 按站点分组 ymst <- c("year", "month", "site", "sample") # 按年、月、站点、样本类型分组 ymt <- c("year", "month", "sample") # 按年、月、样本类型分组 st <- c("site", "sample") # 按站点、样本类型分组 # 分组条件列表,通过索引编号调用 filter_list <- list( ymsd , ymsdc , ymsdt , ymsdct, yms , ym , s , ymst , ymt , st )
当前尝试的代码及问题
我尝试用以下代码执行分组求和,分组逻辑是有效的,但无法实现按组求和:无论怎么调用列名,计算出的都是整列的总和,而非每组内的求和结果。我需要针对不同分组条件执行不同计算(涉及3个dataframe和大量变量),cumsum无法满足需求。
代码如下:
# 将sheet的第9列列名存入全局变量tosum assign("tosum",colnames(.GlobalEnv$sheet[9])) sheet <- sheet %>% group_by_at(unlist(.GlobalEnv$filter_list[2])) %>% mutate( total = sum(.GlobalEnv$tosum) )
注:sheet是从多工作表Excel文件中读取的一个dataframe。
数据示例
附其中一个工作表的部分数据:
| date | year | month | site | depth | ncore | type | DW | BW |
|---|---|---|---|---|---|---|---|---|
| 2021-10-19 00:00:00 | 2021 | Oct | SB | 12 | 1 | BG | 0.441 | 0.209 |
| 2021-10-19 00:00:00 | 2021 | Oct | SB | 12 | 1 | AG | 0.306 | 0.142 |
| 2021-10-19 00:00:00 | 2021 | Oct | SB | 12 | 1 | DT | 2.19 | 1.65 |
内容的提问来源于stack exchange,提问作者Tiriyon
相关产品推荐
相关产品推荐

