[英]How to create sub-matrices in R?
I have a matrix "Mat.return" with 390 rows and 2749 columns and I want to create 2499 sub-matrices from it, each with 250 columns and 80 rows. 我有一个包含390行和2749列的矩阵“ Mat.return”,我想从中创建2499个子矩阵,每个子矩阵有250列和80行。
The first sub-matrix would be: 第一个子矩阵为:
B1=(Mat.return)[sample(nrow((Mat.return)),size=80,replace=TRUE),][,c(1:250)]
The second one, would start from the second column of "Mat.return" and would select 250 following columns. 第二个将从“ Mat.return”的第二列开始,然后选择250列。 It would thus be:
因此它将是:
B2=(Mat.return)[sample(nrow((Mat.return)),size=80,replace=TRUE),][,c(2:251)]
The third one would start from the third column and would select the 250 following column, and so on [until matrix n°2499] 第三列将从第三列开始,然后选择250列,依此类推[直到矩阵n°2499]
Is there a function or a code that could do this, instead of computing it manually? 是否有功能或代码可以执行此操作,而不是手动计算?
Thank you! 谢谢!
Just make a loop from 1 to 2499 around your function. 只需围绕您的函数在1到2499之间循环即可。 this code will give you a list of 2499 matrix on 80 rows and 251 columns
此代码将为您提供80行和251列的2499矩阵列表
Mat.return <- matrix(rnorm(390*2749), nrow = 390, ncol = 2749)
lmat <- lapply(1:2499, function(i){
(Mat.return)[sample(nrow((Mat.return)),size=80,replace=TRUE),][,c(i:(250 + i))]
})
str(lmat, list.len = 10)
#> List of 2499
#> $ : num [1:80, 1:251] 0.493 -0.295 2.299 -1.427 -0.174 ...
#> $ : num [1:80, 1:251] -0.4 -1.632 1.21 0.529 -1.045 ...
#> $ : num [1:80, 1:251] -1.71 -1.458 0.186 0.808 -1.179 ...
#> $ : num [1:80, 1:251] 0.237 -0.952 -0.632 -0.204 -1.702 ...
#> $ : num [1:80, 1:251] -1.828 -0.895 -1.31 1.009 -0.451 ...
#> $ : num [1:80, 1:251] 0.128 0.461 -0.393 0.358 1.549 ...
#> $ : num [1:80, 1:251] -0.44814 0.52248 0.28651 0.39365 -0.00774 ...
#> $ : num [1:80, 1:251] 0.136 0.615 -0.435 -0.846 0.788 ...
#> $ : num [1:80, 1:251] 0.761 0.11 -1.486 -0.488 0.118 ...
#> $ : num [1:80, 1:251] -0.9064 -1.3382 -0.9678 0.0654 -0.5952 ...
#> [list output truncated]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.