2
$\begingroup$

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,

$\endgroup$
4
  • 2
    $\begingroup$ This is pretty much a duplicate of this question and this question. Maybe there should be a community wiki entry for this? $\endgroup$
    – atiretoo
    Commented Jul 6, 2012 at 20:58
  • $\begingroup$ 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. $\endgroup$ Commented Jul 7, 2012 at 9:42
  • $\begingroup$ @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. $\endgroup$
    – chl
    Commented Jul 7, 2012 at 9:50
  • $\begingroup$ Fine by me. It is clearly a duplicate. And borderline stackoverflow in any case. $\endgroup$ Commented Jul 7, 2012 at 9:51

2 Answers 2

5
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.