【问题标题】:Same operation (division) by groups for all columns in RR中所有列的相同操作(除法)
【发布时间】:2021-12-06 17:43:47
【问题描述】:

我有一个像 Christmas 这样的数据集:

Christmas <- data_frame(month = c("1", "1", "2", "2"), 
                 NP = c(2, 3, 3, 1),
                 ND = c(4, 2, 0, 6),
                 NO = c(1, 5, 2, 4),
                 variable = c("mean", "sd", "mean", "sd"))

我想按月计算每列的 t 统计量。 我想使用的 t-statistic 公式是 t-statistic = mean/sd。 (注意:我想为所有(在这种情况下,它们只是 NP、ND 和 NO)列进行计算)。

新数据集将类似于 t_statistics

t_statistic <- data_frame(
  month = c("1", "2"), 
  NP = c(2/3, 3),
  ND = c(4/2, 0),
  NO = c(1/5, 2/4)
  )

有什么线索吗?

【问题讨论】:

    标签: r testing dplyr multiple-columns division


    【解决方案1】:

    如果我们已经创建了mean/sd 值,那么它只是first 元素除以last(因为每个组只有两行)

    library(dplyr)
    out <- Christmas %>% 
        group_by(month) %>% 
        summarise(across(NP:NO,  ~first(.)/last(.)))
    

    -输出

    out
    # A tibble: 2 × 4
      month    NP    ND    NO
      <chr> <dbl> <dbl> <dbl>
    1 1     0.667     2   0.2
    2 2     3         0   0.5
    

    -检查 OP 的输出

    > identical(t_statistic, out)
    [1] TRUE
    

    或者如果mean/sd 没有排序

    Christmas %>%
       arrange(month, variable) %>%
       group_by(month) %>%
       summarise(across(NP:NO,  ~first(.)/last(.)))
    

    【讨论】:

    • 明确引用“mean”和“sd”允许任何排序:Christmas %&gt;% group_by(month) %&gt;% summarize(across(NP:NO, ~.[variable == "mean"]/.[variable == "sd"]))
    • @JoshGray 这也是可能的,但示例显示已订购
    • 很好的解决方案@akrun,感谢您提供有用的解决方案@JoshGray!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多