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
CodePudding user response:
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
CodePudding user response:
Using base R
as.list(cor(df)[1,-1])
-output
$e
[1] 1
$Age
[1] 1
