我们可以在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_split 和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
或将base R 与split 和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