【问题标题】:excluding grouping to run a statistical test in tidyverse排除分组以在 tidyverse 中运行统计测试
【发布时间】:2021-05-22 17:39:48
【问题描述】:

我想知道为什么我在下面的mshapiro_test() 调用会引发错误?

我希望此调用在我的数据中排除变量 IDGroup

library(tidyverse)
library(rstatix)

d <- read_csv("https://raw.githubusercontent.com/rnorouzian/v/main/memory.csv")

d %>% group_by(Group) %>% select(-ID) %>%  mshapiro_test()

#Error: Problem with `mutate()` input `data`.
#x is.numeric(x) is not TRUE

【问题讨论】:

    标签: r dataframe dplyr statistics tidyverse


    【解决方案1】:

    我们可以在summarise 中使用cur_data()

    library(dplyr)
    d %>%
       select(-ID) %>% 
       group_by(Group) %>% 
       summarise(out = list(mshapiro_test(cur_data())))
    

    -输出

    # A tibble: 3 x 2
    #  Group out             
    #* <chr> <list>          
    #1 CON   <tibble [1 × 2]>
    #2 HI    <tibble [1 × 2]>
    #3 MT    <tibble [1 × 2]>
    

    out 是一个 list 列。可以是unnested

    library(tidyr)
    d %>%
        select(-ID) %>% 
        group_by(Group) %>% 
        summarise(out = list(mshapiro_test(cur_data()))) %>%
        unnest(c(out))
    # A tibble: 3 x 3
    #  Group statistic p.value
    #  <chr>     <dbl>   <dbl>
    #1 CON       0.907   0.122
    #2 HI        0.963   0.599
    #3 MT        0.947   0.412
    

    cur_data() 只选择不是分组的列

    d %>% 
      select(-ID) %>%
      group_by(Group) %>%
      summarise(out = list(head(cur_data(), 2))) %>%
      pull(out)
    [[1]]
    # A tibble: 2 x 2
         MP    SE
      <dbl> <dbl>
    1     4     6
    2     6     4
    
    [[2]]
    # A tibble: 2 x 2
         MP    SE
      <dbl> <dbl>
    1    10     7
    2     7     8
    
    [[3]]
    # A tibble: 2 x 2
         MP    SE
      <dbl> <dbl>
    1     6     9
    2     7     9
    

    或者另一个选项是group_splitmap

    library(purrr)
    d %>% 
        select(-ID) %>% 
        group_split(Group, .keep = FALSE) %>% 
        map_dfr(mshapiro_test)
    # A tibble: 3 x 2
    #  statistic p.value
    #      <dbl>   <dbl>
    #1     0.907   0.122
    #2     0.963   0.599
    #3     0.947   0.412
    

    或将base Rsplitsapply/lapply 一起使用

    sapply(split(d[3:4], d$Group), mshapiro_test)
    #           CON       HI        MT       
    #statistic 0.9070134 0.9627111 0.9470829
    #p.value   0.1218592 0.5993172 0.4120478
    

    【讨论】:

    • @rnorouzian 只是mshapiro_test 的输出不是一列。因此,必须将其包装在 list
    • 现在答案是正确的分组拆分。
    • @rnorouzian 因为您传递的是字符串向量,而不是您可能需要的数据集的列with(d, sapply(split(d[c("MP","SE")], Group), mshapiro_test)) split 使用with 可以获得列的值,如果它没有被引用..对于多列,您可能需要cbinddata.frame
    • @rnorouzian 你可以transpose 并使用column_to_rownames将列转换为行名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2012-10-17
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    相关资源
    最近更新 更多