How to Correlate one variable to all other variables on R

user3071533 picture user3071533 · Dec 5, 2013 · Viewed 36.5k times · Source

I want to correlate one variable (say tyrosine) with all the other variables (about 200 other metabolites, like urea, glucose, inosine, etc) on R, and I'm not sure how to go about it. I'm new to R.

I've learned the pair function, but that pairs every metabolite in the range specified to the other.

Thanks!

Answer

jlhoward picture jlhoward · Dec 5, 2013

Since you mention "metabolites", I assume your metric is "concentration", e.g. that you have a matrix, call it data that has one column for every metabolite, and one row for every sample.

So, something like this:

# just generates example - YOU SHOULD PROVIDE THIS!!!
data <- data.frame(tyrosine=1:10 + rnorm(10,sd=2), 
                   urea    =2*1:10 + rnorm(10,sd=2),
                   glucose =30 -2*1:10 +rnorm(10,sd=2),
                   inosine =25 -1:10 + rnorm(10,sd=2))
data
     tyrosine      urea  glucose  inosine
1  -0.2529076  5.023562 29.83795 26.71736
2   2.3672866  4.779686 27.56427 22.79442
3   1.3287428  4.757519 24.14913 22.77534
4   7.1905616  3.570600 18.02130 20.89239
5   5.6590155 12.249862 21.23965 17.24588
6   4.3590632 11.910133 17.88774 18.17001
7   7.9748581 13.967619 15.68841 17.21142
8   9.4766494 17.887672 11.05850 16.88137
9  10.1515627 19.642442 11.04370 18.20005
10  9.3892232 21.187803 10.83588 16.52635

To get correlation coefficients, just type:

cor(data)
           tyrosine       urea    glucose    inosine
tyrosine  1.0000000  0.8087897 -0.9545523 -0.8512938
urea      0.8087897  1.0000000 -0.8577782 -0.8086910
glucose  -0.9545523 -0.8577782  1.0000000  0.8608000
inosine  -0.8512938 -0.8086910  0.8608000  1.0000000

To generate a scatterplot matrix, just type:

pairs(data)

In future, please include an example of your data that can be imported into R.