Dear all, Thanks very much for your help. This completely clarifies my question. Mayteo Il giorno 23/dic/2015 17:05, "Anthoni, Peter (IMK)" <peter.anth...@kit.edu> ha scritto:
> Hi, > > How about the following: > foo2 <- function(s,i,j,value) > { > M = get(paste("M_",s,sep="")) > M[i,j] = value > assign(paste("M_",s,sep=""),M, envir = .GlobalEnv) > } > > foo2("a",1,2,15) > > cheers > Peter > > > On 23 Dec 2015, at 09:44, Matteo Richiardi <matteo.richia...@gmail.com> > wrote: > > > > 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@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. > > [[alternative HTML version deleted]] ______________________________________________ R-help@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.