简体   繁体   中英

Maintaining names while flattening lists in R

Below is some dummy data and code. I think I'm trying to do the exact opposite to this question.

After manipulating for a statistical test , I'm left with a very ugly looking list. When I unpack this list as per this method with unlist , the variable/country coding stored in names is totally lost.

I would like to have a data frame with countries as row names and categories as column names.

Any pointers would be much appreciated!

set.seed(1)

CVtest <- list()

for (i in c("AT","BE","DE")) { #For all countries

  # Test all categories together

  CVtest[[i]][["EveryCat"]] <-  sample(seq(0, 1, by=0.01), 1)

    for (j in c("All", "Sub", "Key", "Sel")) { # Test each category

      CVtest[[i]][[j]] <- sample(seq(0, 1, by=0.01), 1)
    }
}

Current output:

> class(CVtest)
[1] "list"
> CVtest

$`AT` EveryCat      All      Sub      Key      Sel 
    0.26     0.37     0.57     0.91     0.20 

$BE EveryCat      All      Sub      Key      Sel 
    0.90     0.95     0.66     0.63     0.06 

$DE EveryCat      All      Sub      Key      Sel 
    0.20     0.17     0.69     0.38     0.77

Desired output

> class(CVtest)
[1] "data.frame"
> CVtest
       EveryCat  All  Sub  Key  Sel
AT     0.26 0.37 0.57 0.91 0.20
BE     0.90 0.95 0.66 0.63 0.06
DE     0.20 0.17 0.69 0.38 0.77

Your question is still not clear (see my latest comment). I can only guess what you want. Could you try:

x <- purrr::transpose(CVtest)
y <- rlist::list.stack(x)
rownames(y) <- names(x)
y

Say me whether y is the desired output. Otherwise I will delete this answer and please clarify your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM