-2

Here's some code:

for(i in 1:colCount){
 for(j in colCount:i){
     cor(newCovidNoNaDF[,i],newCovidNoNaDF[,j], method = "pearson")
 }
}

But nothing is output when I click enter. What am I doing wrong?

2 Answers2

1

You can use combn. Taking mtcars as example :

val <- combn(seq_along(mtcars), 2, function(x) 
             cor(mtcars[[x[1]]], mtcars[[x[2]]], method = 'pearson'))
name <- combn(names(mtcars), 2, paste0, collapse = '-')
data <- data.frame(name, val)

head(data)

#      name        val
#1  mpg-cyl -0.8521620
#2 mpg-disp -0.8475514
#3   mpg-hp -0.7761684
#4 mpg-drat  0.6811719
#5   mpg-wt -0.8676594
#6 mpg-qsec  0.4186840
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

The correlate() function from the corrr package computes pairwise column correlations for a dataframe:

library(corrr)

correlate(df)

Output:

Correlation method: 'pearson'
Missing treated using: 'pairwise.complete.obs'

# A tibble: 3 x 4
  term       a      b      c
  <chr>  <dbl>  <dbl>  <dbl>
1 a     NA      0.182  0.223
2 b      0.182 NA     -0.262
3 c      0.223 -0.262 NA    

Data:

set.seed(123)
n <- 20
df <- tibble(a = rnorm(n), b = rnorm(n), c = rnorm(n))
andrew_reece
  • 20,390
  • 3
  • 33
  • 58