'How can I extract multiple matrices of different sizes from a Loop in R?
I'm a beginner in R and programming in general. I have been trying to extract my data all day, but can't seem to do so. I have a loop similar to,
MyData<-list()
for (i in 1:91){
for (j in 1:50){
Process<-A[j:50,i]*2
myData[i]<-Process
}
}
So, A is a matrix that consists of 91 columns, each represent a certain period, from 1-91. The rows on the other hand, represent the number of objets from that period, that is, 50 total per period. Process, defines the result for the loop, so every iteration by period must produce a matrix of j(1:50)rows for i(1:91)periods. If I were to eliminate j, then,
MyData<-matrix(ncol = 91,nrow = 50)
for (i in 1:91){
Process<-A[,i]*2
myData[,i]<-Process
}
this gives me a matrix of 91 columns by 50 rows, so this is ok. The problem is that I cannot extract my data, when I define j, my objective is to get 50 matrices each of 91 columns but the number of rows will change given j. How can I extract my data?, as you see in the first example I tried using a list, but so far none have given me the right results.
Solution 1:[1]
If I understand correctly, I think you are trying to generate 50 matrices in this manner:
MyData<-list()
for (j in 1:50) {
Process<-A[j:50,,drop=F]*2
MyData[[j]]<-Process
}
}
Of course, this can be done in one line like this:
MyData = lapply(1:50, function(j) A[j:50,,drop=F]*2)
Input:
set.seed(123)
A = matrix(rpois(91*50, 20),nrow=50, ncol=91)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
