简体   繁体   中英

How to calculate correlation In R

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

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

You can use by function eg:

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM