Hi, I don't understand why this doesn't work: matTest <- matrix(nrow=3, ncol=3) testMove <- function(I, J){ for(i in 1:I){ for(j in 1:J){ matTest[i, j] <- i+j } } } testMove(2, 3) matTest Why the elements of the matrix matTest are still NA? How could I fix it? Thanks, Ken
Wacek Kusnierczyk
2008-Jun-21 06:37 UTC
[R] unable to update the matrix values within a function
Ken Liu wrote:> Hi, > > I don't understand why this doesn't work: > > matTest <- matrix(nrow=3, ncol=3) > testMove <- function(I, J){ > for(i in 1:I){ > for(j in 1:J){ > matTest[i, j] <- i+j > } > } > } > testMove(2, 3) > matTest > > Why the elements of the matrix matTest are still NA? How could I fix it? > >i'm afraid it won't work this was, because the assignment is done on a copy of matTest local to the function. here's a simpler example: x=1 (function() x=2)() # x is still 1 you can fix your code with 'assign': sumfill = function(I,J) { for (i in 1:I) for (j in 1:J) matTest[i,j]=i+j; assign("matTest", matTest, parent.frame()) } sumfill(3,3) # matTest is filled a generic version of sumfill, if that's what you need, could be implemented as sumfill = function(m) { n=deparse(substitute(m)); d=dim(m); for (i in 1:d[1]) for (j in 1:d[2]) m[i,j]=i+j; assign(n,m,parent.frame()) } have fun. vQ