【问题标题】:How to calculate correlation In R如何计算R中的相关性
【发布时间】:2011-10-09 06:30:56
【问题描述】:

我想计算 R 中数据集 x 的子集的列之间的相关系数 我有 40 个模型的行,每行 200 个模拟,总共 8000 行 我想计算每个模拟的列之间的相关系数(40 行)

cor(x[c(3,5)]) 从所有 8000 行计算
我需要cor(x[c(3,5)]) 但只有在X$nsimul=1 等时才需要

在这方面你能帮我吗 圣

【问题讨论】:

  • cor(x[X$nsimul==1,c(3,5)]) ?如果没有可重现的例子,这个问题很难回答。

标签: r correlation


【解决方案1】:

我不确定你到底在用 x[c(3,5)] 做什么,但看起来你想做如下的事情:你有一个这样的数据框 X

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

并且您想通过nsimul 列拆分此数据框,并计算每个组中ab 之间的相关性。这是一个经典的split-apply-combine 问题,plyr 包非常适合:

require(plyr)
> ddply(X, .(nsimul), summarize, cor_a_b = cor(a,b))
  nsimul    cor_a_b
1      1 -0.7549232
2      2 -0.5964848

【讨论】:

    【解决方案2】:

    你可以使用by函数例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多