I have a correlation table from a book that I want to import into R.
The ultimate goal is to convert this correlation matrix into a covariance matrix using the cor2cov
function. However, in order to do that, I need to read in all these values into a corr.mat
data type first. How do I do that? Do I read in the values as a dataframe first? Or as vectors?
Thank you!
CodePudding user response:
The function cov
gives back the covariance matrix between x and y (Here I added x2 to show you that you can do that with multiple variables). You can transform your covariance matrix to a correlation matrix with cov2cor(df)
Use ?cor
to get more details about the function.
library(stats)
x <- seq(1,10,1)
x2 <- seq(1,20,2)
y <- c(0,0,0,0,0,0,1,1,1,1)
df <- data.frame(x,x2,y)
print(cov(df))
x x2 y
x 9.166667 18.333333 1.3333333
x2 18.333333 36.666667 2.6666667
y 1.333333 2.666667 0.2666667