I am not very familiar with using the list function in R. This is my first use of a list of matrices. I am trying to remove the same columns from each matrix in a list of matrices but I am not sure how this works with the indexing in R.
Right now I have 8 matrices in a list. Each matrix is [120, 56]. I would like to remove rows columns 17-40 and 49-56 from each matrix. Therefore, I would end up with a list of 8 matrices of [120, 24].
Here is an example of the matrix list I have:
MatrixList <- list(maxT = matrix(1:56, 120, 56, byrow = TRUE),
minT = matrix(1:56, 120, 56, byrow = TRUE),
meanT = matrix(1:56, 120, 56, byrow = TRUE),
rain24 = matrix(1:56, 120, 56, byrow = TRUE),
rain5d = matrix(1:56, 120, 56, byrow = TRUE),
maxT2 = matrix(1:56, 120, 56, byrow = TRUE),
minT2 = matrix(1:56, 120, 56, byrow = TRUE),
meanT2 = matrix(1:56, 120, 56, byrow = TRUE))
I know this seems like a simple problem but I’m a novice and am just not sure how to use a combination of for loops and internal indexing to remove columns. I’d rather learn how to do this efficiently, rather than doing it for each matrix individually and then creating the list.
Any help would be appreciated. Thanks!
As is often the case, @DWin gets in early with an excellent answer. Here is an alternative that my simple mind finds easier to comprehend.
You can use
lapplyto traverse your list, and then standard subsetting using the[operator.Rather than using
[operator as a function (as @DWin suggests), I prefer writing an anonymous function insidelapplythat looks exactly like the operation you would perform to transform a single element of your list (i.e. subset a single matrix):