Re: [R] Simple loop

From: Petr Savicky <savicky_at_praha1.ff.cuni.cz>
Date: Wed, 04 May 2011 09:50:59 +0200

On Tue, May 03, 2011 at 12:04:47PM -0700, William Dunlap wrote: [...]
> ave() can deal that problem:
> > cbind(x, newCol2 = with(x, ave(H, Site, Prof,
> FUN=function(y)y-min(y))))
> Site Prof H newCol2
> 1 1 1 24 8
> 2 1 1 16 0
> 3 1 1 67 51
> 4 1 2 23 0
> 5 1 2 56 33
> 6 1 2 45 22
> 7 2 1 67 21
> 8 2 1 46 0
> Warning message:
> In min(y) : no non-missing arguments to min; returning Inf
> The warning is unfortunate: ave() calls FUN even for when
> there is no data for a particular group (Site=2, Prof=2 in this
> case).

The warning may be avoided using min(y, Inf) instead of min().

  cbind(x, newCol2 = with(x, ave(H, Site, Prof, FUN=function(y)y-min(y,Inf))))

    Site Prof H newCol2

  1    1    1 24       8
  2    1    1 16       0
  3    1    1 67      51
  4    1    2 23       0
  5    1    2 56      33
  6    1    2 45      22
  7    2    1 67      21
  8    2    1 46       0

Another approach is to combine Site, Prof to a single column in any way suitable for the application. For example

  cbind(x, newCol2 = with(x, ave(H, paste(Site, Prof), FUN=function(y)y-min(y))))

Petr Savicky.



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 Thu 05 May 2011 - 06:25:12 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 Thu 05 May 2011 - 07:00:06 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