This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Converting elements of a nested list into individual data frames in R

The nested list contains 3 different lists that I need to convert to individual dataframe. Any suggestions?

x <- round(matrix(rexp(480 * 10, rate=.1), ncol=6), 0)

rownames(x) <- paste("gene", 1:nrow(x))

colnames(x) <-c("control1","control2","control3","treated","treated","treated")


(controls <- colnames(x)[startsWith(colnames(x),"cont")])

(nested_list <- lapply(controls, function(n){
  colnames(x)[which(colnames(x)==n)] <- "ignoreme"
  x
}))

nested_list

I have tried rbind and cbind that gives one big dataframe instead.

nested dataframe r list

I would like to help, but you have to elaborate a bit more on what you want to achieve?

If I copy and paste your code as it is, I get nested_list with elements of the type matrix:

lapply(nested_list,class)
[[1]]
[1] "matrix" "array"

So if you want to convert each matrix to a data.frame,

lapply(nested_list,as.data.frame)

will do so. But I guess you are actually looking for a different output?

Hi, Thank you Matthias for your help. So now you know that there are three lists within Nested list. I want to convert each of them to a separate dataframe. So in the end, I will have three dataframes (dataframe1 coming from list[[1]], dataframe2 coming from list[[2]] and dataframe3 coming from list[[3]]).

I need these different dataframes for different downstream analysis.

Hope it helps.

Best, Salman

Technically, my answer above was correct then, because as.data.frame() does the conversion of a matrix to a data.frame. However, it keeps them stored within a list, so they can be serially processed more easily. If you want to break the list structure, you can mostly use unlist() or sapply(), if the list's elements can be stored e.g. in a regular character vector.

For a data.frame, however, indeed you can't, so you need to assign each separately to the Global Environment:

mapply(function(element, index) {
  assign(
    x = paste0("dataframe", index),
    value = as.data.frame(element),
    env = globalenv()
  )
  return(NULL)
}, nested_list, seq_along(nested_list))

I hope this solves your issue. Best,

Matthias

Thank you Matthias, It is really helpful explanation.

Regards

0 answers

No answers yet.

Log in to answer this question.