Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract certain parts of nested lists of a list to create a dataframe

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading