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

From: Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk_at_idi.ntnu.no>
Date: Sat, 21 Jun 2008 08:46:00 +0200

Wacek Kusnierczyk wrote:
> 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.
>

... but the preferred style, i think, would be sth like:

sumfill = function(I,J) { m=matrix(nrow=I,ncol=J); for (i in 1:I) for (j, 1:J) m[i,j]=i+j; m }
testMat = sumfill(3,3)

vQ



R-help_at_r-project.org mailing list
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. Received on Sat 21 Jun 2008 - 06:48:11 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 21 Jun 2008 - 07:30:48 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive