3

I wanted to calculate correlation coeficient between colunms of a subset of a data set x in R I have rows of 40 models each 200 simulations in total 8000 rows I wanted to calculate the corr coeficient between colums for each simulation (40 rows)

cor(x[c(3,5)]) calculates from all 8000 rows
I need cor(x[c(3,5)]) but only when X$nsimul=1 and so on

would you help me in this regards San

skaffman
  • 398,947
  • 96
  • 818
  • 769
san
  • 31
  • 1
  • 2

2 Answers2

6

I'm not sure what exactly you're doing with x[c(3,5)] but it looks like you want to do something like the following: You have a data-frame X like this:

set.seed(123)
X <- data.frame(nsimul = rep(1:2, each=5), a = sample(1:10), b = sample(1:10))

> X
   nsimul  a  b
1       1  1  6
2       1  8  2
3       1  9  1
4       1 10  4
5       1  3  9
6       2  4  8
7       2  6  5
8       2  7  7
9       2  2 10
10      2  5  3

And you want to split this data-frame by the nsimul column, and calculate the correlation between a and b in each group. This is a classic split-apply-combine problem for which the plyr package is very well-suited:

require(plyr)
> ddply(X, .(nsimul), summarize, cor_a_b = cor(a,b))
  nsimul    cor_a_b
1      1 -0.7549232
2      2 -0.5964848
Prasad Chalasani
  • 19,912
  • 7
  • 51
  • 73
0

You can use by function e.g.:

correlations <- as.list(by(data=x,INDICES=x$nsimul,FUN=function(x) cor(x[3],x[5])))

# now you can access to correlation for each simulation
correlations["simulation 1"]
correlations["simulation 2"]
...
correlations["simulation 40"]
digEmAll
  • 56,430
  • 9
  • 115
  • 140