Converting elements of a nested list into individual data frames

This nested list contains 3 different lists that I need to convert to individual dataframes.

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

data_frame <-as.data.frame(do.call (cbind, nested_list))

But it gives one single large data frame. Does anyone have some suggestions please?

Hi @saad1490,

I am not entirely sure what you're hoping to do, but it you want to iterate over items (in this case matrices) in a list to convert them to data frames, this should do it:

lapply(nested_list, as.data.frame)

This will return a list of data frames, rather than a list of matrices. Hope this helps.

Hi,
Sorry about the confusion. I would like to have 3 data frames separately.
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.

Try this:

purrr::iwalk(
  .x = nested_list,
  .f = function(x, y) {
    x <- as.data.frame(x)
    y <- paste0('dataframe', y)
    assign(y, x, envir = globalenv())
  }
)
1 Like

Thank you that works perfectly!
I appreciate your time and help.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.