D Jay
D Jay

Reputation: 99

Correlation of subsets in a data frame

I am trying to calculate Correlation of two variables belong to subset of a data frame and here is the data samples:

  Participant<-c("A01", "A01", "A01","A01","A01","A01","A02","A02", "A02", "A02","A02","A02")
  TechnicalQuality<-c(4.20, 2.25, 2.75, 1.67 , 1.50 , 4.11, 2.50 , 2.00, 2.50 , 2.40 , 3.25, 3.10  )
  GrandMean<-c(2.7375, 2.7375, 2.3300, 2.3300, 2.9900, 2.9900, 2.7375, 2.7375, 2.3300, 2.3300, 2.9900, 2.9900)
  Master = data.frame(Participant, TechnicalQuality, GrandMean)

I need compute correlation between Grandmean and TechnicalQuality for each Participant, in the sample they are A01 and A02, and would like to save the correlation result to a new data frame for further process.

Just wondering if there is any good way to do this in R? Since I have 30 participant and about 600 rows in my original data?

Thanks for any advice!

Upvotes: 0

Views: 707

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

You can use by:

by(Master[-1], Master[[1]], FUN = function(x) cor(x[1], x[2]))
# Master[[1]]: A01
# [1] 0.2662404
# ------------------------------------------------------------- 
# Master[[1]]: A02
# [1] 0.6048852

Upvotes: 2

Related Questions