[R] Apply a function to each cell of a ragged matrix

Liaw, Andy andy_liaw at merck.com
Wed Feb 18 00:26:07 CET 2004


> sapply(split(x,f), sum)
daytime   night 
     12       9 

HTH,
Andy

> From: XIAO LIU
> 
> R-Helpers:
> 
> There are a matrix x and a factor f.  nrow(x) == length(f), e.g.:
> x <- matrix(1:6, nrow = 3)
> f <- factor(c("daytime", "daytime", "night"))
> 
> I want the sum of all elements of rows of "x" for each 
> corresponding level in factor "f",
> In this case, I want output like:
> "daytime" [1] x[1,1]+x[2,1]+x[1,2]+x[2,2]
> "night"   [2] x[3,1]+x[3,2]
> 
> But, tapply(x,f,sum) or by(x,f,sum) do not work.  What other 
> functions can I use?
> 
> Thank you very much
> 
> Xiao


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}




More information about the R-help mailing list