R语言dplyr按诊断类型汇总数值求和报错求助
按诊断类型汇总数值总和的问题排查与解决
原始数据
site diagnosis week value Site A anxiety total 13 Site B anxiety total 1 Site A depression total 27 Site C depression total 18
需求
按diagnosis(诊断类型)汇总所有value(数值)的总和,忽略site和week字段,用于后续绘图。
尝试的代码与报错
尝试代码
df %>% group_by(diagnosis) %>% summarize( total = sum(value, na.rm = TRUE))
报错信息
"Error in
summarize():
! Problem while computingtotal_value = sum(n, na.rm = TRUE).
ℹ The error occurred in group 1: diagnosis = "anxiety".
Caused by error insum():
! invalid 'type' (closure) of argument
Runrlang::last_error()to see where the error occurred."
错误原因分析
报错提示sum(n, na.rm = TRUE)出问题,说明你实际运行的代码里,误将sum(value, ...)写成了sum(n, ...)。而n在dplyr环境中是内置函数n()(用于统计行数),属于closure(闭包/函数类型),sum()无法对函数类型的参数求和,因此抛出"invalid 'type' (closure) of argument"错误。
正确实现代码
确保调用sum()时传入的是数据框中的value列,完整代码如下:
library(dplyr) # 若你的df已存在,可跳过构造示例数据这一步 df <- data.frame( site = c("Site A", "Site B", "Site A", "Site C"), diagnosis = c("anxiety", "anxiety", "depression", "depression"), week = rep("total", 4), value = c(13, 1, 27, 18) ) # 按diagnosis汇总value总和 summary_df <- df %>% group_by(diagnosis) %>% summarize(total = sum(value, na.rm = TRUE)) # 查看汇总结果 print(summary_df)
运行结果
# A tibble: 2 × 2 diagnosis total <chr> <dbl> 1 anxiety 14 2 depression 45
内容的提问来源于stack exchange,提问作者Jackie
相关产品推荐
相关产品推荐

