r - 在 for 循环中剪切数字变量
问题描述
我正在努力循环遍历数字列名称列表,使用 cut() 和 group_by() 来通过其他变量的 bin 来总结“e”。下面的代码给出了错误“'x'必须是数字”,参考变异步骤。
library(dplyr)
df <- data.frame(a = round(rnorm(50, 1,1.5),2),
b = round(rnorm(50, 1,1.5),2),
c = round(rnorm(50, 1,1.5),2),
d = round(rnorm(50, 1,1.5),2),
e = round(rnorm(50, 1,1.5),2))
nums <- colnames(df[,1:4])
for (i in nums) {
summary <- df %>%
mutate(z = cut(i, seq(min(i),max(i),length.out = 10), include.lowest = TRUE)) #%>%
group_by(z) %>%
summarise(e = sum(e))
}
谢谢!
解决方案
试试这个方法
x <- letters[1:4] %>%
purrr::set_names()
sum_grp_fun <- function(x){
df %>%
mutate(grp = cut(.data[[x]],
seq(min(.data[[x]]),max(.data[[x]]),length.out = 10),
include.lowest = TRUE)) %>%
group_by(grp) %>%
summarise(e = sum(e))
}
map(.x = x, ~ sum_grp_fun(.x))
推荐阅读
- mysql - mysql加入子查询问题
- android - 获取android中回调“外部”变量的值
- python - DataFrame多目标排序来定义帕累托边界
- python - 为什么用小数求幂时负 numpy.float64 会产生 nan?
- python - 使用 pandas read_csv 读取标题时跳过`#`字符
- python - 具有 sizing_mode 属性的 Python Holoviews 响应式图表
- c - 读取 PMG P5 文件的错误
- python - 覆盖运算符以处理无类型
- node.js - Vimeo APi、私人链接和受密码保护的视频
- javascript - 我需要在 Foreach 上传递变量吗?