Reputation: 295
I want to find the correlations between variables. I have data set like this
ID A B C
[1,] 1 1 1 0
[2,] 2 0 0 1
[3,] 3 1 0 0
[4,] 4 1 0 1
And I want to use cor() function and get this:
cor_AB cor_AC cor_BC
[1,] 0.5 0.012 0.46
Upvotes: 0
Views: 236
Reputation: 6778
The following should get you what you want:
set.seed(9025)
dat = data.frame(id=1:4, a=rnorm(4), b=rnorm(4), c=rnorm(4))
dat
# id a b c
# 1 1 1.0339032 1.1523611 0.6029744
# 2 2 1.5605713 -0.4773037 0.7484699
# 3 3 1.5165112 1.8949990 -1.5356641
# 4 4 -0.5837422 -1.1165541 0.2414511
x = cor(dat[, -1])
x
# a b c
# a 1.0000000 0.6377170 -0.2289408
# b 0.6377170 1.0000000 -0.6468663
# c -0.2289408 -0.6468663 1.0000000
cors = x[lower.tri(x)]
cors
# [1] 0.6377170 -0.2289408 -0.6468663
Upvotes: 2