[R] aggregation-type question

Rui Barradas ruipbarradas at sapo.pt
Fri Feb 8 17:44:28 CET 2013


Hello,

With the following, the first instruction will give you correlations 
matrices, the second coefficients.

dat <- read.table(text = "
          x         y group
1 0.876751503 0.6518345     a
2 0.627067150 0.8801790     a
3 0.632465192 0.1768305     a
4 0.060359554 0.8835652     a
5 0.675868776 0.7721177     a
6 0.008465241 0.5046486     a
", header = TRUE)
str(dat)

lapply(split(dat[, c("x", "y")], dat$group), cor)
lapply(split(dat[, c("x", "y")], dat$group), function(d) cor(d$x, d$y))


Hope this helps,

Rui Barradas

Em 08-02-2013 16:33, carslaw escreveu:
> I seem to have a Friday afternoon block and can't see the easiest way of
> doing this.
>
> Given a data frame like:
>
> dat <- data.frame(x = runif(100), y = runif(100), group = rep(letters[1:10],
> each = 10))
>> head(dat)
>              x         y group
> 1 0.876751503 0.6518345     a
> 2 0.627067150 0.8801790     a
> 3 0.632465192 0.1768305     a
> 4 0.060359554 0.8835652     a
> 5 0.675868776 0.7721177     a
> 6 0.008465241 0.5046486     a
>
> I want to work out cor(x, y) by group, so in this case ending up with 10
> correlation coefficients by group.
>
> I'm not seeing a straightforward solution and I'd appreciate your help.
>
> Thanks
>
> David
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/aggregation-type-question-tp4657966.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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.
>



More information about the R-help mailing list