This is my dataset,
df1 <- "ID t res
1 1 -1.5
1 2 -1.5
1 3 0.5
1 4 0.5
2 1 -0.5
2 2 -0.5
2 3 -2.0
2 4 -1.5
2 5 1.5"
df1 <- read.table(text = df1, header = TRUE)
What I like to do is,
Covert this to a matrix.
Transform from long to wide
ID 1 2 3 4 5 1 -1.5 -1.5 0.5 0.5 NA 2 -0.5 -0.5 -2.0 -1.5 1.5
Finally Create a 5 x 5 covariance matrix like this.
1 2 3 4 5 0.5 0.5 -1.25 -1 0 0.5 0.5 -1.25 -1 0 -1.25 -1.25 3.125 2.5 0 -1 -1 2.5 2 0 0 0 0 0 0
I am able to do this with a dataframe , using functions pivot_wide
or reshape
and cov
which is manual and tedious. However i am not sure how to perform these steps when the data object is a matrix. Any suggestion is very helpful. Thanks.