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

Doran, Harold HDoran at air.org
Wed Jan 13 18:16:50 CET 2010


with(yourdataframe, tapply(age,sex,mean))

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of John Sorkin
Sent: Wednesday, January 13, 2010 12:11 PM
To: r-help at r-project.org
Subject: [R] Applying function to parts of a matrix based on a factor

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:9}}



More information about the R-help mailing list