[R] Adding elements in an array where I have missing data.

Berton Gunter gunter.berton at gene.com
Tue May 2 20:43:42 CEST 2006


That is curious, as I thought when I checked it that evalq did what I said
by default. Apparently not. However, to continue in the vein of complex
solutions for simple problems, either

explicitly using local() or specifying a local environment as an argument

 evalq({a[is.na(a)]<-0;a},env=new.env())+b 

does it. Either must be used to protect against argument evaluation, which
is the point of interest.

The solutions you suggested do this implicitly by creating local function
environments in which the assignment occurs of course.

This also means that my arcane explanation of evaluation is wrong: the
evaluator does not by default do the assignment in a local environment as I
stated, but follows the pointers (enclosures) -- of course. Local evaluation
must be explicitly forced. 

-- Bert
 
 

> -----Original Message-----
> From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
> Sent: Tuesday, May 02, 2006 11:14 AM
> To: Berton Gunter
> Cc: John Kane; R R-help
> Subject: Re: [R] Adding elements in an array where I have 
> missing data.
> 
> But the evalq solution does change a.
> 
> > a <- c(2, NA, 3)
> > b <- c(3,4, 5)
> > evalq({a[is.na(a)]<-0;a})+b
> [1] 5 4 8
> > a
> [1] 2 0 3
> 
> If evalq were changed to local then it would not change a:
> 
> > a <- c(2, NA, 3)
> > b <- c(3,4, 5)
> > local({a[is.na(a)]<-0;a})+b
> [1] 5 4 8
> > a
> [1]  2 NA  3
> 
> Also the replace, ifelse and mapply solutions do not change a.
> 
> 
> On 5/2/06, Berton Gunter <gunter.berton at gene.com> wrote:
> > Below.
> >
> > > -----Original Message-----
> > > From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com]
> > > Sent: Tuesday, May 02, 2006 10:42 AM
> > > To: Berton Gunter
> > > Cc: John Kane; R R-help
> > > Subject: Re: [R] Adding elements in an array where I have
> > > missing data.
> > >
> > > On 5/2/06, Berton Gunter <gunter.berton at gene.com> wrote:
> > > > >
> > > > > Here are a few alternatives:
> > > > >
> > > > > replace(a, is.na(a), 0) + b
> > > > >
> > > > > ifelse(is.na(a), 0, a) + b
> > > > >
> > > > > mapply(sum, a, b, MoreArgs = list(na.rm = TRUE))
> > > > >
> > > >
> > > > Well, Gabor, if you want to get fancy...
> > > >
> > > > evalq({a[is.na(a)]<-0;a})+b
> > > >
> > >
> > > Note that the evalq can be omitted:
> > >
> > >    { a[is.na] <- 0; a } + b
> > >
> >
> > No it can't. The idea is **not** to change the original a.
> >
> > -- Bert
> >
> >
>




More information about the R-help mailing list