[R] Intraindividual means, SDs, and n's

arun smartpink111 at yahoo.com
Thu Mar 13 16:29:53 CET 2014


Hi,
Try:
 set.seed(42)
 dat1 <- data.frame(Happy=sample(c(NA,1:25),40,replace=TRUE),ID=rep(1:5,each=8))

 with(dat1,ave(Happy,ID,FUN=function(x) sum(!is.na(x))))
#or
library(plyr)
 ddply(dat1,.(ID),mutate,mean=mean(Happy,na.rm=TRUE),SD=sd(Happy,na.rm=TRUE),n=sum(!is.na(Happy)))



#or you could use:
library(psych)
with(dat1,describeBy(Happy,ID,mat=TRUE))[,4:6]
#   n     mean       sd
#11 8 15.75000 7.611082
#12 8 16.25000 6.296257
#13 8 16.12500 9.508455
#14 8 15.00000 7.230886
#15 6 15.16667 6.765107

A.K.







I am creating variables representing intraindividual means and standard 
deviations for longitudinal data with the following code: 

data$TraitHAPPYmean <- with(data, ave(Happy, ID, FUN=function(x) mean(x, na.rm=TRUE) )  ) 

& 

data$TraitHAPPYsd <- with(data, ave(Happy, ID, FUN=function(x) sd(x, na.rm=TRUE) )  ) 

I'd like to also create a variable that just returns the # of 
cases for each grouping variable (ID). For example, some IDs might have 
10 cases of Happy (the target measure here), while others have only 5. 

I realize that this is probably a very basic question, but I just cannot figure it out! Thanks.



More information about the R-help mailing list