Converting elements of a nested list into individual data frames in R
0
0
Entering edit mode
2.2 years ago
salman_96 ▴ 70

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 • 2.4k views
ADD COMMENT
0
Entering edit mode

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?

ADD REPLY
0
Entering edit mode

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

ADD REPLY
1
Entering edit mode

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

ADD REPLY
0
Entering edit mode

Thank you Matthias, It is really helpful explanation.

Regards

ADD REPLY

Login before adding your answer.

Traffic: 2646 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6