Tpellirn
Tpellirn

Reputation: 796

Calculate correlations between data.frame columns and assign output to list

Given this data.frame:

 Age <- c(23, 41, 32, 58, 26)
 e <- c(23, 41, 32, 58, 26)
 Ag <- c(23, 41, 32, 58, 26)
 df <- data.frame(Ag,e, Age)

I would like to use cor to compute the correlation between Ag and all other columns in the data.frame (they are many not only two). Then return the results in a list with names of columns as

>lst
$e
[1] 1

$Age
[1] 1

Upvotes: 1

Views: 42

Answers (2)

akrun
akrun

Reputation: 887741

Using base R

as.list(cor(df)[1,-1])

-output

$e
[1] 1

$Age
[1] 1

Upvotes: 2

user438383
user438383

Reputation: 6227

Using dplyr.

summarise allows us to select which columns to apply a custom function to - in this case, all columns other than Ag, with the custom function performing the correlation between Ag and the selected ones.

library(dplyr)
df %>% summarise(across(-Ag, function(x) cor(x, Ag))) %>% as.list
$e
[1] 1

$Age
[1] 1

Upvotes: 2

Related Questions