データフレームの列を集約することにより、相関を計算します
-
27-10-2019 - |
質問
次のデータフレームがあります。
y <- data.frame(group = letters[1:5], a = rnorm(5) , b = rnorm(5), c = rnorm(5), d = rnorm(5) )
各行の列a、b、c、dの相関を与えるデータフレームを取得する方法は?
何かのようなもの: sapply(y, function(x) {cor(x[2:3],x[4:5])})
ありがとうございます
解決
使用できます apply
> apply(y[,-1],1,function(x) cor(x[1:2],x[3:4]))
[1] -1 -1 1 -1 1
または ddply
(これはやり過ぎかもしれませんが、2行が同じ場合 group
これらの両方の行に対して列A&BとC&Dの相関を実行します):
> ddply(y,.(group),function(x) cor(c(x$a,x$b),c(x$c,x$d)))
group V1
1 a -1
2 b -1
3 c 1
4 d -1
5 e 1
他のヒント
使用できます apply
マトリックス、配列、またはdata.frameの各行(または列)に関数を適用します。
apply(
y[,-1], # Remove the first column, to ensure that u remains numeric
1, # Apply the function on each row
function(u) cor( u[1:2], u[3:4] )
)
(2回の観測では、相関は+1または-1のみになります。)
あなたはほとんどそこにいます:あなたはただ使用する必要があります apply
それ以外の sapply
, 、不要な列を削除します。
apply(y[-1], 1, function(x) cor(x[1:2], x[3:4])
もちろん、2つの長さ2ベクトル間の相関関係はあまり有益ではありません。
所属していません StackOverflow