[R] assigning values to elements of matrixes

Matteo Richiardi matteo.richiardi at gmail.com
Wed Dec 23 09:44:35 CET 2015


I am following the example I find on ?assign:

a <- 1:4
assign("a[1]", 2)

This appears to create a new variable named "a[1]" rather than
changing the value of the vector.

Am I missing something here? How can I assign a value to a specified
element of a vector/matrix?

Of course, my problem is slightly more involved, but I guess the above
is its core. For those interested, I have the two matrixes
M_a <- matrix(0,10,10)
M_b <- matrix(0,10,10)

I want to have a function that assigns a value to a specific element
of one of the matrix, as in
foo <- function(s,i,j,value){
  assign(paste("M_",s)[i,j],value)
}

This however does not work:

foo('a',1,1,1)

Error in paste("M_", s)[1, j] : incorrect number of dimensions

Following the ?assign help, I tried

foo2 <- function(s,i,j,value){
  assign(paste("M_",s,"[i,j]"),value, envir = .GlobalEnv)
}

but this produces the problem I described above (namely, a new
variable is created, rather than replacing the specified element of
the matrix).

I know that in this example I could simply pass the matrix as an
argument to the function, but I am interested in understanding how
'assign' work.

Many thanks for your help.

Matteo



More information about the R-help mailing list