upInCloud
upInCloud

Reputation: 1009

R - Slicing a matrix in R column wise in for loop

I have a matrix bigDaddy of dimensions nrow=20, ncol=1000. Now I have a for loop where I want to run 100 iterations and in each iteration, I want to get a slice of 10 columns and all rows of bigDaddy. e.g. in first iteration, all rows and columns 1-10, in second iteration all rows and columns 11-20 and so on.

Here's the code I'm trying:

for(i in seq(from=1, to 991, by=10))
{
    smallChild <- bigDaddy[,i:i+9]
}

but what's smallChild giving me in first iteration is a 20 length vector created from 10th column of matrix bigDaddy. If i hardcode the value of i in the code like smallChild <- bigDaddy[,1:10], I get the expected matrix.

Can someone point me to the correct direction?

Upvotes: 0

Views: 4472

Answers (2)

Parfait
Parfait

Reputation: 107687

Consider using lapply to save a list of objects as opposed to many separate (similarly structured) objects:

data_list <- lapply(seq(from=1, to=991, by=10), function(i) bigDaddy[,i:(i+9)])

Even give the items names:

data_list <- setNames(data_list, paste0("SmallChild_", seq(length(data_list))))

data_list$SmallChild_1
data_list$SmallChild_2
data_list$SmallChild_3
...

And if you really want separate objects run list2env on a named list of objects:

list2env(data_list, .GlobalEnv)

Upvotes: 0

user3640617
user3640617

Reputation: 1576

You can use assign to save each SmallChild under a different name, e.g. SmallChild1, SmallChild11, etc.

for(i in seq(from=1, to 991, by=10))
{
    temp <- bigDaddy[,i:(i+9)]
    assign(paste0(SmallChild, i), temp)
}

Upvotes: 1

Related Questions