excluding grouping to run a statistical test in tidyverse

Viewed 30

I was wondering why my mshapiro_test() call below throws an error?

I want this call to exclude variables ID and Group in my data.

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
1 Answers

We can use cur_data() within summarise

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

-output

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

The out is a list column. It can be 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

The cur_data() only selects the columns that are not the grouping

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

Or another option is group_split with map

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

Or using base R with split and sapply/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
Related