Below I apply shapiro test on the first 4 columns of iris dataset. I would like to create a dataframe out of this with the column name, the p value and the w score.
apply(iris,2,shapiro.test)
>Solution :
You can do this:
df <- apply(iris[,1:4], 2, function(x) {
sh <- shapiro.test(x)
c(p = sh$p.value, sh$statistic)})
Sepal.Length Sepal.Width Petal.Length Petal.Width
p 0.01018116 0.1011543 7.412263e-10 1.680465e-08
W 0.97609027 0.9849179 8.762681e-01 9.018349e-01
You can make it tidy dataframe as follow:
library(tidyverse)
as.data.frame(df) %>%
rownames_to_column(var = "stats") %>%
pivot_longer(cols = -stats)
# A tibble: 8 x 3
stats name value
<chr> <chr> <dbl>
1 p Sepal.Length 1.02e- 2
2 p Sepal.Width 1.01e- 1
3 p Petal.Length 7.41e-10
4 p Petal.Width 1.68e- 8
5 W Sepal.Length 9.76e- 1
6 W Sepal.Width 9.85e- 1
7 W Petal.Length 8.76e- 1
8 W Petal.Width 9.02e- 1