[R] apply a function over a factor

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Dec 29 19:33:58 CET 2009


have a look at ?ave(), e.g.,

A <- 1:10
B <- factor(c(1,2,2,4,4,4,7,7,7,7))

ave(A, B)


I hope it helps.

Best,
Dimitris


faridamsb at gmail.com wrote:
> Dear R experts,
> 
> I would like to substitute the values of a vector, say A, with the average  
> values taken over a factor
> 
> For example, lets assume
> 
> 
> A
> 
> [1] 1 2 3 4 5 6 7 8 9 10
> 
> B
> 
> [1] 1 2 2 4 4 4 7 7 7 7
> Levels: 1 2 4 7
> 
> I need to have
> 
> 1.0 2.5 2.5 5.0 5.0 5.0 8.5 8.5 8.5 8.5 8.5
> 
> Thank you
> 
> 	[[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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list