To input a correlation matrix for SEM in R, I need to reformat a matrix in three ways:
In other words, the matrix...
EDU CLASS INCOME AUTONOMY COL5 ALT5 IIDM
EDU 1.00000000 -0.14591135 0.246463592 0.21938208 -0.09727587 -0.043862753 0.062896738
CLASS -0.14591135 1.00000000 -0.048511437 -0.01469029 0.01663138 0.036140650 -0.010155653
INCOME 0.24646359 -0.04851144 1.000000000 0.13778603 -0.06969773 -0.051922861 0.009402784
AUTONOMY 0.21938208 -0.01469029 0.137786034 1.00000000 -0.25223015 0.023174980 0.073941520
COL5 -0.09727587 0.01663138 -0.069697725 -0.25223015 1.00000000 -0.300825028 -0.062978212
ALT5 -0.04386275 0.03614065 -0.051922861 0.02317498 -0.30082503 1.000000000 0.001553936
IIDM 0.06289674 -0.01015565 0.009402784 0.07394152 -0.06297821 0.001553936 1.000000000
... needs to become the text...
1.00000000
-0.14591135 1.00000000
0.24646359 -0.04851144 1.000000000
0.21938208 -0.01469029 0.137786034 1.00000000
-0.09727587 0.01663138 -0.069697725 -0.25223015 1.00000000
-0.04386275 0.03614065 -0.051922861 0.02317498 -0.30082503 1.000000000
0.06289674 -0.01015565 0.009402784 0.07394152 -0.06297821 0.001553936 1.000000000
... to be inputted line-by-line into the readMoments function, as shown below.
R.bd <- readMoments(names=c('EDU',
'CLASS',
'INCOME',
'AUTONOMY',
'COL5',
'ALT5',
'IIDM'))
1.00000000
-0.14591135 1.00000000
0.24646359 -0.04851144 1.000000000
0.21938208 -0.01469029 0.137786034 1.00000000
-0.09727587 0.01663138 -0.069697725 -0.25223015 1.00000000
-0.04386275 0.03614065 -0.051922861 0.02317498 -0.30082503 1.000000000
0.06289674 -0.01015565 0.009402784 0.07394152 -0.06297821 0.001553936 1.000000000
We are currently doing this manually by copying, deleting, and pasting. Any suggestions on how to go about writing a function to do this would be greatly appreciated.
Thanks, Jonathan
You can create the object R.bd
directly. You don't need to input line by line.
Assuming, dat
is the name of the object (data frame or matrix):
dat[upper.tri(dat)] <- 0 # replace all elements above the diagonal with 0
R.bd <- as.matrix(dat) # transform to matrix (not necessary if it's a matrix)
That's it. You don't need to specify the names since they are already in the matrix object.