0

I have a list of lists, ex.final_list, in which element is a list like below:

final_list[[1]]
`S1`
`S1`[[1]]
"path1"      "0.0896894915174206"
`S1`[[2]]
"path2"      "0.205873598055805"
.... 
and so on.

So, I want to have a dataframe with rows as the number of length final_list (which as I mentioned is very large most of the time), and columns number is always 344. In each cell of this dataframe the float number should be saved. There is my code here for doing this:

S_df <- matrix(0, nrow = 42845, ncol = 344)
rownames(S_df) <- unique(names(final_list))
colnames(S_df) <- colnames(paths)
  for(i in 1:42845){
    print(i)
    row_name <- names(final_list[1])
    temp_lst <- final_list[[1]]
    for(j in 1:length(temp_lst)){
      S_df[which(rownames(S_df) == row_name), which(colnames(S_df) == temp_lst[[j]][1])] <- temp_lst[[j]][2]
    }
  }

This takes a lot time (more than 1 hour and half!!!). Therefore, I would be thankful if anybody has any suggestion for improving the time of my code.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Nmgh
  • 113
  • 7
  • 1
    Would you provide small amount of reproducible example? It will be very helpful to look up to your problem. [how to make reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Park Sep 06 '21 at 07:18
  • Provide example data as `dput`, and expected output. Read about `stack`, `lapply`, `rbind`. – zx8754 Sep 06 '21 at 07:41
  • Does `final_list %>% bind_rows()` give you what you want? [You'll need `library(tidyverse)` as well. Otherwise, as @Park writes, we will need more information to help you. – Limey Sep 06 '21 at 07:48
  • From your printout, it looks like you don't have float numbers, the quotes around it make it look like you have character vectors. A small reproducible example would help a lot to make sure we get the data types right. `sample_list = list(final_list[[1]][1:3], final_list[[2]][1:3]); dput(sample_list)` might make a good reproducible example, if I'm interpreting your question right. – Gregor Thomas Sep 06 '21 at 15:13

0 Answers0