Reputation: 159
Okay, so I have the following list on R:
seg_sites list[1000] List of length 1000
[[1]] double [40x162] 00000000000000000000000...
[[2]] double [40x150] 11110000000000000000000...
[[3]] double [40x160] 00000000111111110000000...
[[4]] double [40x93] 00110000000000111100000...
[[5]] double [40x144] 00000110000000000110000...
...
And the list goes on for a thousand entries. As you can see, I always have the same number of rows but I have different number of columns for each entry. What I want to do, is extract each entry to a single matrix. For example, I want to create a matrix called "output_1" containing the information the [[1]] entry, then output_2 with the information from the [[2]] entry and so on.
I was trying to use a for loop for this:
# Loop to intialize the matrices where I want to store the different entries
for(i in 1:nrep) {
output_single_i <- matrix(data = NA, nrow = 40, ncol = ncol(single[["seg_sites"]][[i]]))
}
# Loop to actually store the different entries in each matrix
for(i in 1:nrep) {
output_single_i <- matrix(single$seg_sites[[i]], ncol = ncol(single[["seg_sites"]][[i]]))
}
What this code is doing is just saving the last entry on the list on a matrix called "output_single_i" but I don't know how to fix it. Any help would be greatly appreciated
Upvotes: 1
Views: 40
Reputation: 12723
we can use assign
to create matrix data from a list of matrices. The matrix data are saved in global environment, which you can inspect using ls()
invisible( lapply(seq_along(mylist), function(x) {
assign( x = paste0("Output", x), value = mylist[[x]], envir = .GlobalEnv )
return(TRUE)
} ))
Another way is to use list2env()
function
names(mylist) <- paste0( 'output', seq_along(mylist))
list2env( mylist, envir = .GlobalEnv)
Data:
mylist <- list(matrix(1:10, ncol = 5), matrix(1:10, ncol = 2))
str(mylist)
# List of 2
# $ : int [1:2, 1:5] 1 2 3 4 5 6 7 8 9 10
# $ : int [1:5, 1:2] 1 2 3 4 5 6 7 8 9 10
Upvotes: 2