【问题标题】:R - dplyr summary over combinations of factorsR - dplyr 对因素组合的总结
【发布时间】:2017-05-25 16:29:45
【问题描述】:

如果我有一个包含 2 个因子(a 和 b)、2 个水平(1 和 2)和 1 个变量 (x) 的简单数据框,我如何获得 x 的中值:每个因子水平的中值 x a,因子 b 的每个水平,以及 a*b 的每个组合?

library(dplyr)    
df <- data.frame(a = as.factor(c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)),
   b = as.factor(c(1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2)),
   x = c(runif(16)))

我尝试了各种(许多)版本:

df %>%
   group_by_(c("a", "b")) %>%
   summarize(med_rate = median(df$x))

每个因子 a 水平的中位数 x 的结果应如下所示:

中位数
1 0.58811
2 0.53167

对于因子 b 的每个水平的中位数 x 如下所示:

b 中位数
1 0.60622
2 0.46096

对于 a 和 b 的每个组合的中位数 x 如下所示:

a b 中位数
1 1 0.66745
1 2 0.34656
2 1 0.50903
2 2 0.55990

提前感谢您的帮助。

【问题讨论】:

  • summarise中取出df$
  • 你不需要引号,你可以使用group_by,即df %&gt;% group_by(a, b) %&gt;% summarize(med_rate = median(x))
  • 谢谢。但这给了我一个中值; 16 次观测的中位数 x。它没有给我每个因素(a 和 b)的每个级别(1 和 2)以及每个 a*b 组合的每个级别的中值。
  • @DavidG 它确实给了我每个级别的中位数,即。 4 个值。也许你也加载了plyr 库。试试df %&gt;% group_by(a, b) %&gt;% dplyr::summarize(med_rate = median9x))
  • 是的!非常感谢!

标签: r dplyr combinations summarize


【解决方案1】:
set.seed(123) ##make your example reproducible
require(data.table)
df <- data.table(a = as.factor(c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)),
             b = as.factor(c(1,1,1,1,2,2,2,2,1,1,1,1,2,2,2,2)),
             x = c(runif(16)))

df[, median(x), by = a]
df[, median(x), by = b]
df[, median(x), by = .(a,b)]

【讨论】:

  • 谢谢;但我收到一条错误消息以响应每个“df [,中值(x),by = z]命令:“未使用的参数(by = z)”
  • 你有一个名为 z 的列吗?
  • 没有。那是速记,所以我不必重复错误消息 3 次:每个命令一次 (by=a; by=b; by=.(a,b)。
  • 你加载data.table了吗?
  • 不,我没有加载 data.table,因为在我的示例中 df 是作为数据框创建的。但我看到您的解决方案适用于数据表。谢谢。
【解决方案2】:

以下不是很优雅,但创建了一个满足您预期结果的data.frame

我们正在创建三个数据 data.frames(用于 a、b 和 a*b)并将它们合并为一个。

bind_rows(
  df %>% 
    group_by(a) %>% 
    rename(factor_g = a) %>% 
    summarize(med_rate = median(x)),
  df %>% 
    group_by(b) %>% 
    rename(factor = b) %>% 
    summarize(med_rate = median(x)),
  df %>% 
    # We create a column for grouping a*b
    mutate(factor = paste(a, b)) %>% 
    group_by(factor) %>% 
    summarize(med_rate = median(x))
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2021-11-16
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 2019-06-26
    相关资源
    最近更新 更多