【问题标题】:Cut numeric vars in for loop在 for 循环中剪切数字变量
【发布时间】:2020-03-03 19:06:32
【问题描述】:

我正在努力遍历数字列名称列表,使用 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))
}

谢谢!

【问题讨论】:

  • 尝试!!ensym(i) 插入i
  • 这就是诀窍 - 在基础 R 中是否有类似的功能?
  • @JackAndrew tidyvers 具有与基础 R 不同的非标准评估 (NSE) 生态系统,请参阅 Programming with dplyr
  • @AaronMontgomery ensym 将字符串转换为符号,然后 !! 在正确的环境/上下文中对其进行评估。

标签: r for-loop dplyr


【解决方案1】:

试试这个方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2021-07-03
    相关资源
    最近更新 更多