[R] how to chage values in data frame to NA iside a function

Petr Pikal petr.pikal at precheza.cz
Tue Feb 25 13:29:05 CET 2003


Thanks a lot. 

If I understand it correctly I shall have some object, preferably 
before I use a function, in which I can make changes and which 
shall have the same name "inside" and "outside" a function (eg. 
df$myvariable)

>dropout<-function(y, nahr=FALSE,...) { 
><some stuff for computing an index> 
>if (nahr) df$myvariable[index]<<-NA 
###############################
or
>if (nahr) df[index,]<<-NA 

>invisible(index) 
}

Changed function works on artificial example. 

On 25 Feb 2003 at 7:57, ripley at stats.ox.ac.uk wrote:

> You are mis-using <<-.  I don't know what you think it does, so please
> look it up.  Using <<- in R/S programming is normally a sign of
> incorrect thinking (but not quite always).  (Also, it behaves
> differently in R and in S which can be a cause of confusion to those
> who know only one of the definitions.)
> 
> On Tue, 25 Feb 2003, Petr Pikal wrote:
> 
> > Thank you for your answers. It works OK but my real question is why
> > my  function behaves differently used on vector and data frame (or
> > matrix or list).  
> 
> > I attached a full version below with some foo data, but basically
> > the function  returns the correct index if applied correctly on any
> > type (list, data frame, matrix,  vector) but it changes values of
> > operand only if operand is a vector. 
> 
> Not so.  It always alters an object called `y'.  It just so happens
> that your vector argument was called `y' and the other cases you tried
> were not.
> 
> > Why please? 
> 
> (Because that is what you asked it to do ....)
> 
> I can see a way to do what I think is your intention (to change the
> object which was passed as the y argument from the parent
> environment), but it is convoluted and against the spirit of a
> functional language, so I won't describe it.
> 

<snip>

> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > http://www.stat.math.ethz.ch/mailman/listinfo/r-help
> > 
> 
> -- 
> Brian D. Ripley,                  ripley at stats.ox.ac.uk
> Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
> University of Oxford,             Tel:  +44 1865 272861 (self) 1 South
> Parks Road,                     +44 1865 272866 (PA) Oxford OX1 3TG,
> UK                Fax:  +44 1865 272595
> 

Petr Pikal
Precheza a.s., Nabř.Dr.E.BeneÜe 24, 750 62 Přerov
tel: +420581 252 257 ; 724 008 364
petr.pikal at precheza.cz; p.pik at volny.cz
fax +420581 252 561




More information about the R-help mailing list