Reputation: 1623
I have matrices stored in variables i create out if strings through
assign( name, matrix(...) )
Now i want to set a single value of this matrix providing its name, the row and col and the new value.
I would have imagined it like this:
get(name, envir = my.env)[x,y] <- value
or
assign(paste(name,"[",x,",",y,"]"),value, envir = my.env)
But both options do not work. Is there any nice way to adress this one particular field of the matrix? My current workaround is to first save the matrix to a variable, set its value and set the matrix back to its original variable. It seems to me it is copying the matrix here as it leads to memory problems (the matrix is very big). I obviusoly would prefer other solutions
Upvotes: 0
Views: 151
Reputation: 1735
Try eval
:
my.env <- new.env()
name = 'd'
x = y = 1
assign(name, matrix(1:4, 2), envir=my.env)
eval(parse(text=paste(name, '[', x, ',', y, '] = ', value)), envir=my.env)
my.env[[name]]
# [,1] [,2]
# [1,] 0 3
# [2,] 2 4
Upvotes: 0
Reputation: 132736
Usually I would use a list
, but you can work with an environment
in pretty much the same way:
my.env <- new.env()
myname <- "mymat"
assign(myname, matrix(1:16, 4), envir = my.env)
my.env[[myname]][1, 1] <- 42
my.env[[myname]]
# [,1] [,2] [,3] [,4]
#[1,] 42 5 9 13
#[2,] 2 6 10 14
#[3,] 3 7 11 15
#[4,] 4 8 12 16
Upvotes: 2