'How can I create a Correlation Matrix with multiple, specific variables?
I have a very large data set, but want to do a correlation matrix with only 10 of the variables in that data set (and rename the variable names to something else)
My current code is looking like this:
#Correlation Function
data.cor = cor(df)
#Correlation Coefficient
data.cor = cor(df, method = "pearson", use = "complete.obs")
#Running Correlation w/ P-Values
install.packages("Hmisc")
library("Hmisc")
data.rcorr = rcorr(as.matrix(df))
data.rcorr
#
data.coeff = data.rcorr$r
data.p = data.rcorr$P
However, 1) it doesn't work 2) i am aware it is just reference the full data set
How can I make it so that I am referencing only those 10 variables and be able to rename the variables?
Thank you beforehand!
Solution 1:[1]
If you have a dataframe, d, you can directly subset in numerous ways. For example, using a vector of variable names, as below:
target_vars = c("v1", "v2", "v7", "v8", "v12")
cor(d[,target_vars], method = "pearson", use="complete.obs")
Output:
v1 v2 v7 v8 v12
v1 1.00000000 0.57761512 -0.22465288 0.6571388 0.06053092
v2 0.57761512 1.00000000 0.08178772 0.4641090 0.14373593
v7 -0.22465288 0.08178772 1.00000000 0.3035047 -0.46410860
v8 0.65713875 0.46410902 0.30350472 1.0000000 -0.48583862
v12 0.06053092 0.14373593 -0.46410860 -0.4858386 1.00000000
Input:
set.seed(123)
d = setNames(as.data.frame(lapply(1:20, \(x) rnorm(10))), paste0("v",1:20))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | langtang |
