extract certain elements from lists of lists

Viewed 40

I have a list that contains outputs from multiple correlation tests

dput(head(corr[1:2]))
list(structure(list(statistic = c(S = 1486), parameter = NULL, 
    p.value = 0.219369570345178, estimate = c(rho = 0.265810276679842), 
    null.value = c(rho = 0), alternative = "two.sided", method = "Spearman's rank correlation rho", 
    data.name = "x$theta.x and x$theta.y"), class = "htest"), 
    structure(list(statistic = c(S = 1852), parameter = NULL, 
        p.value = 0.699151237307271, estimate = c(rho = 0.0849802371541502), 
        null.value = c(rho = 0), alternative = "two.sided", method = "Spearman's rank correlation rho", 
        data.name = "x$theta.x and x$theta.y"), class = "htest"))

I would like to extract into a separate data frame p.value and estimate. For each element I can do it like this:

corr[[1]][3]
$p.value
[1] 0.2193696

> corr[[1]][4]
$estimate
rho 
0.2658103 

But I did not have any success in trying to extract those values from the entire list at once.

3 Answers

We can also use extract function from magrittr package for this purpose:

library(purrr)

df %>% map_dfr(magrittr::extract, c("estimate", "p.value"))

# A tibble: 2 x 2
  estimate p.value
     <dbl>   <dbl>
1   0.266    0.219
2   0.0850   0.699

We could do

do.call(rbind, lapply(corr, \(x) data.frame(x[3:4])))
       p.value   estimate
rho  0.2193696 0.26581028
rho1 0.6991512 0.08498024

You can use [ to extract specific element.

as.data.frame(t(sapply(corr, `[`, c(3, 4))))

#  p.value estimate
#1   0.219    0.266
#2   0.699    0.085

Moreover, using broom::tidy might be simpler.

purrr::map_df(corr, broom::tidy)

#  estimate statistic p.value method                          alternative
#     <dbl>     <dbl>   <dbl> <chr>                           <chr>      
#1   0.266       1486   0.219 Spearman's rank correlation rho two.sided  
#2   0.0850      1852   0.699 Spearman's rank correlation rho two.sided  
Related