matrix1 <- matrix(1:25, 5,5)
matrix2 <- matrix(26:50, 5,5)
Suppose, I want to subset the first 3 columns of the above matrices,
list2env(
setNames(
lapply(mget(ls(pattern="matrix")), `[`, ,1:3),
paste("new", ls(pattern="matrix"),sep="_")),
envir=.GlobalEnv)
new_matrix1
# [,1] [,2] [,3]
#[1,] 1 6 11
#[2,] 2 7 12
#[3,] 3 8 13
#[4,] 4 9 14
#[5,] 5 10 15
new_matrix2
# [,1] [,2] [,3]
# [1,] 26 31 36
# [2,] 27 32 37
# [3,] 28 33 38
# [4,] 29 34 39
# [5,] 30 35 40
ls(pattern="matrix") will output [1] "matrix1" "matrix2"
mget get the values stored in the above matrices as a list
- Subset the first 3 columns of matrices in list using
lapply(...,[,1:3)
- Change the name of the list elements from
matrix1, matrix2 by using setNames and paste
- Use
list2env to create new objects new_matrix1, new_matrix2. However, in your case, this would create 472 new_matrices in the global environment. I would prefer to subset the matrices in a list do all the necessary calculations within the list. Then you could use write.table or write.matrix from library(MASS) to write the list elements to file.