你至少需要 tidyverse 来处理 purrr 和 dplyr。
我在示例中制作了更多样本,因为您需要 shapiro.test 的向量而不是单个比率。所以这里有 100 个来自正态分布、二项分布和均匀分布的样本。
library(tidyverse)
Type <- c("Bark", "Redwood", "Oak")
size <- c(10,15,13)
width <- c(3,4,5)
Ratio <- c(rnorm(100),
rbinom(100, size = 2, prob = 0.2),
runif(100))
将这些放在 data.frame 中
# Need minimum sample size for shapiro test
df <- data.frame(Type = rep(Type, each = 100),
Size = rep(size, each = 100),
width = rep(size, each = 100),
Ratio)
然后您可以使用 ratio_log,在这种情况下,我冒昧地使用相同的比率。您可以按Type 分组,并使用nest 为每组嵌套一个data.frame。
df %>%
mutate(ratio_log = Ratio) %>%
group_by(Type) %>%
mutate(N_Samples = n()) %>%
nest()
# A tibble: 3 x 2
Type data
<fct> <list>
1 Bark <tibble [100 x 5]>
2 Redwood <tibble [100 x 5]>
3 Oak <tibble [100 x 5]>
然后您可以使用map 函数和mutate 基本上将lapply 应用于嵌套的data.frames(或小标题,这里基本上相同。)对于每个组的每个data.frame,我们应用shapiro.test 函数到ratio_log 列中的值。
# Use purrr::nest and purrr::map to do shapiro tests per group
df.shapiro <- df %>%
mutate(ratio_log = Ratio) %>%
group_by(Type) %>%
mutate(N_Samples = n()) %>%
nest() %>%
mutate(Shapiro = map(data, ~ shapiro.test(.x$ratio_log)))
# A tibble: 3 x 3
Type data Shapiro
<fct> <list> <list>
1 Bark <tibble [100 x 5]> <S3: htest>
2 Redwood <tibble [100 x 5]> <S3: htest>
3 Oak <tibble [100 x 5]> <S3: htest>
现在您已经嵌套了shapiro.test 结果,应用于每个组。
要获取相关参数,您可以使用broom 包中的glance。然后unnest 来自glance 函数的结果。
# Use broom::glance and purrr::unnest to get all relevant statistics
library(broom)
df.shapiro.glance <- df.shapiro %>%
mutate(glance_shapiro = Shapiro %>% map(glance)) %>%
unnest(glance_shapiro)
Type data Shapiro statistic p.value method
<fct> <list> <list> <dbl> <dbl> <fct>
1 Bark <tibble [100 x 5]> <S3: htest> 0.967 1.30e- 2 Shapiro-Wilk normality test
2 Redwood <tibble [100 x 5]> <S3: htest> 0.638 2.45e-14 Shapiro-Wilk normality test
3 Oak <tibble [100 x 5]> <S3: htest> 0.937 1.31e- 4 Shapiro-Wilk normality test