Home > Mobile >  Extracting estimates from double nested list
Extracting estimates from double nested list

Time:04-13

I am trying to extract the CIs (confidence intervals) from a double-nested list that looks as follows: enter image description here

I am able to do so with the following very ugly code:

library(dplyr)
library(reshape2)
cis <- as.data.frame(L1.estimates[["CIs"]])
cil <- cis[1,]
cil <- melt(cil)
cil <- cil %>% dplyr::select(-c(1)) %>% dplyr::rename(conf.low = 1)
cih <- cis[2,]
cih <- melt(cih)
cih <- cih %>% dplyr::select(-c(1)) %>% dplyr::rename(conf.high = 1)
CIs <- cbind(cil,cih)

However, it produces the following warning: "No id variables; using all as measure variables". What is the cleaner way to do what I did? There is clearly a better way.

CodePudding user response:

Reduce can be used to collapse lists.

l <- list(
  L1 = list(
    Xs = 1:5,
    coefs = 1:5,
    CI = list(1:2, 3:4, 5:6)
    )
)

Reduce(rbind.data.frame, l$L1$CI) |> setNames(c("low", "high"))
#>   low high
#> 1   1    2
#> 2   3    4
#> 3   5    6

CodePudding user response:

A purrr approach:

library(purrr)
library(dplyr)
l %>% 
  map( ~.x[contains("CI", vars = names(.x))]) %>% 
  bind_rows() %>% 
  tidyr::separate(col = "CI", into = c("low", "high"), sep = ":")
  • Related