如何在R语言中将多个同维度矩阵的单元格值合并为单个单元格值为列表的矩阵?
Hey there! Let's walk through how to combine those three matrices into a new one where each cell holds a list of the corresponding values from each input matrix. Here's a straightforward, easy-to-follow way to do it in R:
Step 1: Recreate the Input Matrices
First, let's code up the three matrices you provided so we have something to work with:
# Matrix 1 mat1 <- matrix(c(31, 5, 4, 8), nrow = 2, ncol = 2, dimnames = list(c("GeneA", "GeneB"), c("GeneA", "GeneB"))) # Matrix 2 mat2 <- matrix(c(5, 5, 14, 8), nrow = 2, ncol = 2, dimnames = list(c("GeneA", "GeneB"), c("GeneA", "GeneB"))) # Matrix 3 mat3 <- matrix(c(30, 45, 14, 7), nrow = 2, ncol = 2, dimnames = list(c("GeneA", "GeneB"), c("GeneA", "GeneB")))
Step 2: Combine into a Matrix of Lists
There are a couple of reliable methods to achieve this—pick the one that fits your workflow best:
Method 1: Using Arrays and apply()
This approach stacks the matrices into a 3D array, then converts each (row, column) position into a list:
# Stack all matrices into a 3D array mat_array <- simplify2array(list(mat1, mat2, mat3)) # Convert each position to a list and reshape into the final matrix result_mat <- matrix(apply(mat_array, c(1, 2), list), nrow = nrow(mat1), ncol = ncol(mat1), dimnames = dimnames(mat1))
Method 2: Direct Mapping with mapply()
If you prefer a more direct route, mapply() can map over each corresponding cell across the three matrices and package the values into a list:
# Use mapply to pair values and wrap in lists, then reshape into a matrix result_mat <- matrix(mapply(function(x, y, z) list(x, y, z), mat1, mat2, mat3), nrow = nrow(mat1), dimnames = dimnames(mat1))
Step 3: Check the Result
When you print result_mat, you'll see the structure matches exactly what you need:
print(result_mat) # Output: # GeneA GeneB # GeneA Integer,3 Integer,3 # GeneB Integer,3 Integer,3
To view the actual values in a specific cell, just index into it—for example:
result_mat["GeneA", "GeneA"] # Returns: [[1]] [1] 31 5 30
Which is the list {31,5,30} you wanted for that position.
内容的提问来源于stack exchange,提问作者Nikita Srivastav

