0

First of all, i'm sorry if this question is so basic. I'm trying just to calculate correlation coefficient from three lines of my dataframe :

df=structure(list(Id = 1:3, V1 = c(27L, 40L, 29L), V2 = c(70L, 
101L, 48L), V3 = c(68L, 84L, 55L), V4 = c(48L, 80L, 39L), V5 = c(58L, 
73L, 38L), V6 = c(80L, 103L, 46L), V7 = c(99L, 115L, 52L), V8 = c(46L, 
82L, 58L), V9 = c(26L, 38L, 33L), V10 = c(13L, 17L, 13L)), .Names = c("Id", 
"V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10"), row.names = c(2L, 
5L, 8L), class = "data.frame")

What i'm doing is to convert these lines to vectors numeric

df=df[-1]

g=as.numeric(df[1,])
h=as.numeric(df[2,])
i=as.numeric(df[3,])

and running correlation 2 per 2:

> cor(g,h)
[1] 0.9530113
> cor(g,i)
[1] 0.7557693
> cor(h,i)
[1] 0.8519315

I made search about this but it seems that there is no such function cor(g,h,i), instead i Cant run cor(df) but it will gives me correlation between all the V1:V10.

In conclusion, is there function that allows me to execute cor(g,h,i) and return to me the three correlation coefficient (0.9530113 , 0.7557693 , 0.8519315) or a more optimised method than mine.

ranell
  • 683
  • 13
  • 29
  • 4
    `cor(t(df[-1]))` will give you the correlation matrix. And you can use `upper.tri` or `lower.tri` to get the correlation like `cor_mat <- cor(t(df[-1])); cor_mat[upper.tri(cor_mat)]` – JasonWang Jan 05 '18 at 17:51
  • 1
    Just to add to @JasonWang 's answer. `d = cor(t(df[,-1])); d[lower.tri(d)]` will give you the result as a vector. – AntoniosK Jan 05 '18 at 17:55
  • 1
    > see this solution [Correlation coefficient using corrlY](https://stackoverflow.com/a/56769078/10574296) – Mahesh Kulkarni Jun 26 '19 at 09:29

2 Answers2

2
# Get the correlation matrix by row
cor(t(df[-1]))
#           2         5         8
# 2 1.0000000 0.9530113 0.7557693
# 5 0.9530113 1.0000000 0.8519315
# 8 0.7557693 0.8519315 1.0000000

# Retrieve the correlation as vector
cor_mat <- cor(t(df[-1]))
cor_mat[upper.tri(cor_mat)]
# [1] 0.9530113 0.7557693 0.8519315
JasonWang
  • 2,414
  • 11
  • 12
1

If you want a function:

corr <-function(data,g,h,i) {
 m <- cor(data[,c(g,h,i)])
 m[upper.tri(m)]
}
Martin C. Arnold
  • 9,483
  • 1
  • 14
  • 22