简体   繁体   English

R-在for循环中在R列中切片矩阵

[英]R - Slicing a matrix in R column wise in for loop

I have a matrix bigDaddy of dimensions nrow=20, ncol=1000 . 我有一个尺寸为nrow=20, ncol=1000的矩阵bigDaddy 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 . 现在,我有一个for循环,我想运行100次迭代,并且在每次迭代中,我都希望得到10列的切片以及bigDaddy所有行。 eg in first iteration, all rows and columns 1-10, in second iteration all rows and columns 11-20 and so on. 例如,在第一次迭代中,所有行和列1-10,在第二次迭代中,所有行和列11-20,依此类推。

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 . 但是smallChild在第一次迭代中给我的是从矩阵bigDaddy第10列创建的20长度向量。 If i hardcode the value of i in the code like smallChild <- bigDaddy[,1:10] , I get the expected matrix. 如果我使用smallChild <- bigDaddy[,1:10]类的代码对i的值进行硬编码,则可以得到期望的矩阵。

Can someone point me to the correct direction? 有人可以指出我正确的方向吗?

You can use assign to save each SmallChild under a different name, eg SmallChild1, SmallChild11, etc. 您可以使用assign给保存每个SmallChild根据不同的名称,如SmallChild1,SmallChild11等。

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

Consider using lapply to save a list of objects as opposed to many separate (similarly structured) objects: 考虑使用lapply保存对象列表,而不是使用许多单独的(结构类似)对象:

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在对象的命名列表上运行list2env

list2env(data_list, .GlobalEnv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM