[R] How to compute within-group mean and sd?

Rui Barradas rui1174 at sapo.pt
Sat Mar 24 18:02:29 CET 2012


Hello,


Reeyarn_李智洋_10928113 wrote
> 
> Hi, I want to run something like
>   SELECT firm_id, count(*), mean(value), sd(value)
>   FROM table
>   GROUP BY firm_id;
> 
> But I have to write a for loop like
>   for ( id in unique(table$firm_id ) {
>     print(paste(  id, mean(table[firm_id == id, "value"])  ))
>   }
> 
> Is there any way to do it easier? Thanks :)
> 
> 
> Best,
> Reeyarn Lee
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help@ 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.
> 

You can use sql with package 'sqldf'.

library(sqldf) # It needs package 'tcltk'
?sqldf

tbl <- data.frame(firm_id=rep(c(1,2), 10), value=rnorm(20))

sqldf("SELECT firm_id, count(*), avg(value), stdev(value)
  FROM tbl
  GROUP BY firm_id;")

I've changed the name of your data.frame because 'table' is an R function.

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/How-to-compute-within-group-mean-and-sd-tp4501504p4501709.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list