[R] Mean using different group for a real r beginner

arun smartpink111 at yahoo.com
Fri May 17 07:57:59 CEST 2013


Hi,
Try either:
tolerance <- read.csv("http://www.ats.ucla.edu/stat/r/examples/alda/data/tolerance1.txt") 

 aggregate(exposure~male,data=tolerance,mean)
 # male exposure
#1    0 1.246667
#2    1 1.120000
#or
 library(plyr)
 ddply(tolerance,.(male),summarize,exposure=mean(exposure))
#  male exposure
#1    0 1.246667
#2    1 1.120000
#or 

with(tolerance,tapply(exposure,list(male),FUN=mean))
#       0        1 
#1.246667 1.120000 

#or

 with(tolerance,by(exposure,list(male),mean))
#: 0
#[1] 1.246667
#------------------------------------------------------------ 
#: 1
#[1] 1.12
#or

 library(data.table)
 tolerance1<- data.table(tolerance)
 tolerance1[,list(exposure=mean(exposure)),by=male]
#   male exposure
#1:    0 1.246667
#2:    1 1.120000
#or
sapply(split(tolerance,tolerance$male),function(x) mean(x$exposure))
#       0        1 
#1.246667 1.120000 

#or
library(psych)
 describeBy(tolerance$exposure,tolerance$male,mat=TRUE)[c(2,5)]
#   group1     mean
#11      0 1.246667
#12      1 1.120000

#or
library(doBy)
summaryBy(exposure~male,data=tolerance,FUN=mean)
 # male exposure.mean
#1    0      1.246667
#2    1      1.120000



A.K.




>Hi there, 
>
>I'm new to R and I think I have hard time getting used to it. 
Before asking my question, I looked on several websites, and while they 
have many  >informations about it,  I did not find clear answer to my 
question. 
>
>So, first of all, I use a web-based data set : 
>
>tolerance <- read.csv("http://www.ats.ucla.edu/stat/r/examples/alda/data/tolerance1.txt") 
>
>RIght now, I'm able to calculate the mean of the variable 
exposure. However, I'm unable to find a parsimonious way of obtaining 
the mean of >exposure, separately for male == 0 and male == 1. The only 
solution I have, for the moment, is: 
>
>
>tolerance_male = tolerance [male ==0, c (1:8)] 
>exposure_male = tolerance_male$exposure 
>mean (tolerance_male$exposure) 
>
>
>tolerance_female = tolerance [male ==1, c (1:8)] 
>exposure_female = tolerance_female$exposure 
>mean (exposure_female) 
>
>While this method work well for a simple calculation, it'll be 
quite unhelpful for more complicated analysis. So, I don't know if 
someone has a simpler >way to do it. 
>
>Thank you!



More information about the R-help mailing list