创建动态分组依据

2024-03-22

df = data.frame(
  A = c(1, 4, 5, 13, 2),
  B = c("Group 1", "Group 3", "Group 2", "Group 1", "Group 2"),
  C = c("Group 3", "Group 2", "Group 1", "Group 2", "Group 3")
)

df %>%
  group_by(B) %>%
  summarise(val = mean(A))

df %>%
  group_by(C) %>%
  summarise(val = mean(A))

而不是为每个独特的集合编写新的代码块group_by我想创建一个循环来迭代df数据框并将结果保存到列表或数据框中。

我想看看特征的平均值如何A分布在各个特征上B and C,无需为数据集中的每个分类特征编写新的代码块。

我试过这个:

List_Of_Groups <- map_df(df, function(i) {
  df %>% 
    group_by(!!!syms(names(df)[1:i])) %>% 
    summarize(newValue = mean(A))
})

Using purrr's map,您可以将指定的代码块应用到所有字符列。基本上你map后面的函数的字符变量的名称

purrr::map(names(df %>% select(where(is.character))), function(i) {
  df %>% 
    group_by(!!sym(i)) %>% 
    summarize(newValue = mean(A))
})

Output

# [[1]]
# A tibble: 3 x 2
#   B       newValue
#   <chr>      <dbl>
# 1 Group 1      7  
# 2 Group 2      3.5
# 3 Group 3      4  
# 
# [[2]]
# A tibble: 3 x 2
#   C       newValue
#   <chr>      <dbl>
# 1 Group 1      5  
# 2 Group 2      8.5
# 3 Group 3      1.5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建动态分组依据 的相关文章

随机推荐