I would like to convert three defined columns (data frame) in one thousand of upper (or lower) matrices of 8 traits each in R. Each matrix is written out row-wise in the dataframe. This is an example:
Dataframe with 3 columns (and 12000 rows). From this I need to have 1000 matrices (triangular):
col1 col2 col3
row1 1 2 3
row2 2 3 4
row3 7 4 5
row4 1 4 5
row5 2 4 5
row6 3 4 5
. . . .
. . . .
. . . .
row12000 1 6 9
I need to convert them to 1000 matrices (triangular) of 8 traits each and put them in a list: Example of converting the data in the dataframe into the first matrix:
trait 1 trait2 trait3 trait4 trait5 trait6 trait7 trait8
trait1: 1(row1 col1)
trait2: 2(row1 col2) 5(row3 col3)
trait3: 3(row1 col3) 1(row4 col1) 3(row6 col1)
trait4: 2(row2 col1) 4(row4 col2) 4(row6 col2) value
trait5: 3(row2 col3) 5(row4 col3) 5(row6 col3) value value
trait6: 4(row2 col3) 2(row5 col1) . value value value
trait7: 7(row3 col1) 4(row5 col2) . value value value value
trait8: 4(row3 col2) 5(row5 col3) . value value value value value
CodePudding user response:
- Collapse rowwise the matrix value the dataframe (
df
) value in a vector (all_values
). - Create group of 36 values and split them in a list.
- Place each of the 36 value in a lower triangular matrix of 8 X 8 and get a list of matrices.
all_values <- c(t(df))
dummmy_matrix <- matrix(nrow = 8, ncol = 8,
dimnames = list(paste0('trait', 1:8), paste0('trait', 1:8)))
matrix_list <- lapply(split(all_values, ceiling(seq_along(all_values)/36)), function(x) {
dummmy_matrix[lower.tri(dummmy_matrix, diag = TRUE)] <- x
dummmy_matrix
})
matrix_list