[R] assigning values to elements of matrixes
Fox, John
jfox at mcmaster.ca
Wed Dec 23 17:09:01 CET 2015
Dear Matteo,
Here's a function that does what you want and that you should be able to adapt to your problem. It does have the disadvantage of copying the object twice (beyond the overhead of assigning to the indexed value):
myassign <- function(x, index, value, envir=.GlobalEnv, ...){
object <- get(x, envir=envir, ...)
object[index] <- value
assign(x, object, envir=envir, ...)
}
Your example:
> a <- 1:4
> myassign("a", 1, 2)
> a
[1] 2 2 3 4
I hope this helps,
John
-----------------------------
John Fox, Professor
McMaster University
Hamilton, Ontario
Canada L8S 4M4
Web: socserv.mcmaster.ca/jfox
> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Matteo
> Richiardi
> Sent: December 23, 2015 3:45 AM
> To: r-help at r-project.org
> Subject: [R] assigning values to elements of matrixes
>
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list