如何在R语言中对9×9矩阵内的分块执行求和操作?
How to Sum Sub-Blocks in a 9×9 Matrix in R
Hey there! Let's walk through how to calculate the sum of sub-blocks in your 9×9 matrix. Since 9 is evenly divisible by 3, we'll focus on splitting the matrix into 3×3 sub-blocks (resulting in a 3×3 matrix of block sums) — this is the most common use case for a matrix like yours.
Method 1: Base R with Index Grouping
This approach uses core R functions to manually define your blocks and calculate sums:
# First, recreate your matrix (for reproducible testing) set.seed(123) m <- matrix(runif(9*9), nrow = 9, ncol=9) # Define the size of each sub-block (3x3 here) block_size <- 3 # Split row and column indices into block groups row_blocks <- split(1:nrow(m), ceiling(1:nrow(m)/block_size)) col_blocks <- split(1:ncol(m), ceiling(1:ncol(m)/block_size)) # Calculate the sum for each combination of row and column blocks block_sum_results <- outer(row_blocks, col_blocks, function(r, c) sum(m[r, c])) # Convert the result to a clean matrix block_sum_matrix <- matrix(block_sum_results, nrow = length(row_blocks), ncol = length(col_blocks)) # View the final block sums block_sum_matrix
What's happening here:
split()groups row/column numbers into chunks of sizeblock_size(e.g., rows 1-3, 4-6, 7-9)outer()iterates over every pair of row and column blocks, usingsum(m[r,c])to calculate the total for each sub-matrix- The final conversion to a matrix gives you a 3×3 output where each value is the sum of one 3×3 sub-block from your original matrix
Method 2: Simplified Base R with tapply()
This is a more concise way using tapply() to group elements by their block membership:
set.seed(123) m <- matrix(runif(81), nrow=9, ncol=9) block_size <- 3 # Create grouping variables for each element's row and column block row_group <- ceiling(row(m)/block_size) col_group <- ceiling(col(m)/block_size) # Calculate sums grouped by row and column block block_sums <- tapply(m, list(row_group, col_group), sum) block_sums
Why this works:
row(m)andcol(m)return the row/column number for every element in the matrixceiling(row(m)/block_size)assigns each element to a row block (1, 2, or 3 for your matrix)tapply()aggregates the matrix values by the combined row and column groups, automatically returning a matrix of block sums
Both methods will give you the same result — pick whichever feels more intuitive for you!
内容的提问来源于stack exchange,提问作者nymuffin
相关产品推荐
相关产品推荐

