[R] applying math/stat functions to rows in data frame

Gavin Simpson gavin.simpson at ucl.ac.uk
Sat Sep 15 18:36:32 CEST 2007


On Sat, 2007-09-15 at 09:02 -0700, Gerard Smits wrote:
> Hi All,
> 
> There are a variety of functions that can be applied to a variable 
> (column) in a data frame: mean, min, max, sd, range, IQR, etc.

But one their own, these are not equivalents to rowMeans, rowSums etc
below.

> 
> I am aware of only two that work on the rows, using q1-q3 as example 
> variables:
> 
> rowMeans(cbind(q1,q2,q3),na.rm=T)   #mean of multiple variables
> rowSums (cbind(q1,q2,q3),na.rm=T)   #sum of multiple variables

If you really want to apply a function to the individual rows of a
matrix-like object then apply() is your friend:

?rowMeans states:

Details:

     These functions are equivalent to use of 'apply' with 'FUN = mean'
     or 'FUN = sum' with appropriate margins, but are a lot faster.

So see ?apply and argument 'margin'. For rows use margin = 1, e.g.:

dat <- matrix(runif(1000), ncol = 100)
apply(dat, 1, mean)
rowMeans(dat)


> 
> Can the standard column functions (listed in the first sentence) be 
> applied to rows, with the use of correct indexes to reference the 
> columns of interest?  Or, must these summary functions be programmed 
> separately to work on a row?

You can only use those functions on a column via subsetting, e.g.:

mean(dat[,4])
min(dat[,4])

If all you want is a single row (the equivalent of what you seem to be
asking) then these also work:

mean(dat[4,])
min(dat[4,])

HTH

G

> 
> Thanks,
> 
> Gerard
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Gavin Simpson                 [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list