user6579764
user6579764

Reputation:

R: Using cor.test on multiple columns on a data frame

It know it seems like a pretty simple question, but I can't find the answer cause i'm new in R programing. I have a df composed by a first ID column (treated and not patients) and several columns of metabolic variables. I'm trying to write a simple script that could allow me to make a spearman correlation of the first column with all the other variables. I've tried with the "apply" function like: apply(df,2,cor) but it does not work thus I imagine i should try to use a for loop...do you have any sugestion to how perform it? thank you all

Upvotes: 2

Views: 5579

Answers (1)

Simon Jackson
Simon Jackson

Reputation: 3184

I just answered a similar question here. Following is brief summary:

Install the corrr package. Then, correlate() your data frame variables and focus() on your variable of choice. Here's an example using mtcars data frame and focusing on the correlations that mpg has with all other variables:

install.packages("corrr")  # though keep eye out for new version coming soon
library(corrr)
mtcars %>% correlate() %>% focus(mpg)


#>    rowname        mpg
#>      <chr>      <dbl>
#> 1      cyl -0.8521620
#> 2     disp -0.8475514
#> 3       hp -0.7761684
#> 4     drat  0.6811719
#> 5       wt -0.8676594
#> 6     qsec  0.4186840
#> 7       vs  0.6640389
#> 8       am  0.5998324
#> 9     gear  0.4802848
#> 10    carb -0.5509251

If you're not familiar with the pipe operator (%>%), you can read the code as:

focus(correlate(mtcars), mpg)

or

x <- correlate(mtcars)
focus(x, mpg)

Upvotes: 6

Related Questions