bic ton
bic ton

Reputation: 1408

how to convert results of a for loop to a list?

I have several files in a directory. I can read them like this:

files <- list.files("C:\\New folder", "*.bin",full.names=TRUE)
for (i in 1:length(files)) {
conne <- file(files[i], "rb")
file  <- readBin(conne, double(), size=4,  n=300*700, signed=TRUE)
file2 <- matrix(data=file,ncol=700,nrow=300)
                           }

I wonder how can I put all the matrices (file2) as a list? For instance:

 m1<-matrix(nrow=4,ncol=2,data=runif(8))
 m2<-matrix(nrow=4,ncol=2,data=runif(8))

I put them in a list as:

ml <- list(m1, m2)

Upvotes: 2

Views: 67

Answers (2)

tblznbits
tblznbits

Reputation: 6778

In addition to akrun's answer, you could also just put them in a list to begin with by taking advantage of the lapply function. Modifying your code just slightly, it would look like this:

files <- list.files("C:\\New folder", "*.bin",full.names=TRUE)

dat <- lapply(1:length(files), function(i) {
  conne <- file(files[i], "rb")
  file  <- readBin(conne, double(), size=4,  n=300*700, signed=TRUE)
  file2 <- matrix(data=file,ncol=700,nrow=300)
  close(conne) # as indicated in the comments below
  return(file2)
})

dat is now a list of all of your matrices. lapply acts as a loop, much like for, and will pass each iteration of its first argument, here 1:length(files), to the function as a parameter. The returned value it gets from the function will be passed to the list called dat as its own element.

Upvotes: 2

akrun
akrun

Reputation: 887118

Assuming that the OP created objects 'm1', 'm2' etc in the global envrironment, we can use mget to get the values of the object in a list by specifying the pattern argument in the ls as 'm' followed by numbers (\\d+).

mget(ls(pattern='m\\d+'))

If the question is to split up a large matrix into chunks

 n <- 4
 lapply(split(seq_len(nrow(m)), 
    as.numeric(gl(nrow(m), n, nrow(m)))),  function(i) m[i,])

Upvotes: 1

Related Questions