WeakLearner
WeakLearner

Reputation: 938

Inputting matrices of varying dimensions in R

I have the following problem, lets say i have a function ss() that produces data that always has 4 columns but differing number of rows, I want to store this output into an array

ss(M[1])  #matrix with 4 cols and 10 rows
ss(M[2])  #matrix with 4 cols and 20 rows
ss(M[3]) #matrix with 4 cols and 40 rows

Then I want to put these together in an array:

J<-array(40,4,3)
for ( i in 1:3){
J[,,i]<-ss(M[i])
}

But what happens is that for the first matrix with 10 rows the values are repeated to fill up the array, I want to have 0s after the data existing in M is filled. I then tried:

J<-array(40,4,3)
for ( i in 1:3){
dims<-dim(ss(M[i]))
J[1:dims[1],1:dims[2],i]<-ss(M[i])
}

But I feel that this method is not that efficient, is there a better way? Is there some way to use apply:

B<-lapply(M, ss)

but this is also extremely slow,( M has 10000 elements)

Upvotes: 0

Views: 30

Answers (1)

vitor
vitor

Reputation: 1250

One way to create your object B without a loop would be:

B <- as.array(lapply(1:3, ss))

If you really want to force all matrices to have 40 rows, filling the non-data elements with zeros, you could create a version of ss() which returns a matrix with that number of rows. As in:

ss <- function(x) {
  m <- matrix(x, nrow = x*10, ncol = 4)
  rbind(m, matrix(0, nrow = 40 - nrow(m), ncol = 4))
}

Upvotes: 1

Related Questions