[R] unable to update the matrix values within a function

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Sat Jun 21 08:37:31 CEST 2008


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



More information about the R-help mailing list