[R] Applying function to parts of a matrix based on a factor

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Jan 13 18:17:38 CET 2010


try this:

with(Data, tapply(Age, Sex, mean))


I hope it helps.

Best,
Dimitris


John Sorkin wrote:
> R 2.9
> Windows XP
> 
> I have a matrix, Data, which contains a factor Sex and a continuous variable Age.
> I want to get mean age by sex. I know I can do this with two statements,
> mean(Data["Age,Data[,"Sex"]=="Male") and  
> mean(Data["Age,Data[,"Sex"]=="Female")
> 
> I know this can be done in a single command, but I can remember how. There is a function that allows another function work within factors, something like
> magicfunction(Data,Factor=Sex). n.b. I know the function I am looking for is not in the lapply, sapply etc. family
> 
> Please put me out of my misery (and senior moment) and remind me what function I should be using. 
> 
> 
> 
> 
> John David Sorkin M.D., Ph.D.
> Chief, Biostatistics and Informatics
> University of Maryland School of Medicine Division of Gerontology
> Baltimore VA Medical Center
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> (Phone) 410-605-7119
> (Fax) 410-605-7913 (Please call phone number above prior to faxing)
> 
> Confidentiality Statement:
> This email message, including any attachments, is for th...{{dropped:6}}
> 
> ______________________________________________
> 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