# How to calculate group statistics in R [duplicate]

Possible Duplicate:
R: compute correlation by group

I have a data set with a 6 or so data points for groups of data.

e.g.:

email_id   date_sent  number_sent  number_of_views  number_of_responses
1           5/4         600            25                6
1           5/5         500            22                8
1           5/6         450            23                4
1           5/7         700            34               12
2           5/5         900            30               10
2           5/6         750            28               11
...


(this is made up data that illustrates the point)

Assuming I have this in a data frame in R, I'd like to write something which will give me stats by group. I'm most interested in the correlation coefficient between some of the columns.

I know how to do this with a data frame that contains only one group:

cor(col1, col2)

but I'd like to learn a technique that will allow me to extract data that looks something like this:

email_id    cor(col3, col4)
1             .73
2             .85
3             .98


and so on.

Thanks,

## marked as duplicate by chlJul 7 '12 at 9:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

• This is pretty much a duplicate of this question and this question. Maybe there should be a community wiki entry for this? – atiretoo Jul 6 '12 at 20:58
• Quite right, and they have some great answers that I've +1ed. It'd be nice if there were a a way to know about other answers, as one would if asking a new question. – conjugateprior Jul 7 '12 at 9:42
• @Conjugate Unfortunately, I am not aware of such facilities on SE sites. I'm closing this as a duplicate, though your response was on the point here. – chl Jul 7 '12 at 9:50
• Fine by me. It is clearly a duplicate. And borderline stackoverflow in any case. – conjugateprior Jul 7 '12 at 9:51

## 2 Answers

Assume your data is in d. A fairly transparent and easy to reuse solution to this task is:

library(plyr)
ddply(d, "email_id", summarise, corr=cor(number_sent, number_of_views))


which will give you a data.frame with email_id and corr as variable names.

Assuming your data frame containing your data is called dat:

aggregate(1:nrow(dat), dat["email_id"], function(idx) {
c("cor(col2, col3)" = cor(dat[[2]][idx], dat[[3]][idx]),
"cor(col2, col4)" = cor(dat[[2]][idx], dat[[4]][idx]))
})


This should get you started.