首页 > 解决方案 > 在 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))
}

谢谢!

标签: rfor-loopdplyr

解决方案


试试这个方法

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))

推荐阅读