Reputation: 13113
I wish to add elements from sequences of matrices. For example,
d <- ifelse(i == 4, matrix1[3,3] + matrix2[3,3] + matrix3[3,3] + matrix4[3,3], matrix5[1,1])
Instead of writing out each sequence of matrices I thought it might be more convenient to create the desired sequence with paste0
and then convert the resulting text
to an expression, something like below. I thought this would make it much easier to generalize the code, perhaps allowing inclusion of a variable number of matrices within a for-loop
at some point.
#
# http://stackoverflow.com/questions/8196109/how-to-convert-a-string-in-a-function-into-an-object
# http://stackoverflow.com/questions/1743698/r-eval-expression
#
z <- eval(parse(text=paste0('matrix',1:4,'[3,3]')), env=.GlobalEnv)
z
However, the above example only returns the element matrix4[3,3]
.
I have tried unsuccessfully to modify the above expression by adding a sum
function as below:
eval(parse(text=c('sum(', paste0('matrix',1:4,'[3,3]'), ')')), env=.GlobalEnv)
eval(sum(parse(text=c(paste0('matrix',1:4,'[3,3]')))), env=.GlobalEnv)
Thank you for any suggestions on how to make this work. Perhaps there is a much easier way.
Below is a fully functional example:
matrix1 = matrix(c( 1, 2, 3,
4, 5, 6,
7, 8, 9), nrow=3, byrow=TRUE)
matrix2 = matrix(c( 10, 20, 30,
40, 50, 60,
70, 80, 90), nrow=3, byrow=TRUE)
matrix3 = matrix(c( 100, 200, 300,
400, 500, 600,
700, 800, 900), nrow=3, byrow=TRUE)
matrix4 = matrix(c( 1000, 2000, 3000,
4000, 5000, 6000,
7000, 8000, 9000), nrow=3, byrow=TRUE)
matrix5 = matrix(c(10000, 20000, 30000,
40000, 50000, 60000,
70000, 80000, 90000), nrow=3, byrow=TRUE)
i <- 1:4
a <- b <- c <- d <- rep(NA,4)
a <- ifelse(i == 1, matrix1[1,1] , matrix2[1,1])
b <- ifelse(i == 2, matrix1[2,2] + matrix2[2,2] , matrix3[1,1])
c <- ifelse(i == 3, matrix1[2,2] + matrix2[2,2] + matrix3[2,2] , matrix4[1,1])
d <- ifelse(i == 4, matrix1[3,3] + matrix2[3,3] + matrix3[3,3] + matrix4[3,3], matrix5[1,1])
a
#[1] 1 10 10 10
b
#[1] 100 55 100 100
c
#[1] 1000 1000 555 1000
d
#[1] 10000 10000 10000 9999
# z should equal 9999 not 9000
z <- eval(parse(text=paste0('matrix',1:4,'[3,3]')), env=.GlobalEnv)
z
Upvotes: 2
Views: 141
Reputation: 66834
I suggest using an array
instead of parsing. You can bind matrices together into an array easily using abind
:
library(abind)
arr <- abind(matrix1,matrix2,matrix3,matrix4,matrix5,along=3)
d <- ifelse(i == 4, sum(arr[3,3,1:4]), arr[1,1,5])
d
[1] 10000 10000 10000 9999
Upvotes: 2