求助:编写R语言函数筛选满足指定非零列数的矩阵行
Hey there! Let's work through this R problem together. I'll show you how to build a custom function that filters your matrix to keep only rows with at least a specified number of columns containing values greater than 0.
Step 1: First, let's recreate your input matrix
This will let us test the function directly with your data:
# Build the example matrix from your question mat <- matrix( data = c(0, 0, 0, 2, 2, 5, 4, 0, 0, 0, 8, 3), nrow = 3, byrow = TRUE, dimnames = list(c("row1", "row2", "row3"), c("Col1", "Col2", "Col3", "Col4")) )
Step 2: Create the custom filtering function
This function takes two arguments: your matrix, and the minimum number of positive-value columns you want to require:
filter_rows_by_positive_cols <- function(matrix_input, min_positive_cols) { # Calculate how many columns have values > 0 for each row positive_col_count <- rowSums(matrix_input > 0) # Keep only rows where the count meets or exceeds your minimum matrix_input[positive_col_count >= min_positive_cols, , drop = FALSE] }
Step 3: Test the function with your requirements
Since your desired output keeps rows with at least 2 positive columns, we'll call the function with min_positive_cols = 2:
# Run the filter filtered_matrix <- filter_rows_by_positive_cols(mat, min_positive_cols = 2) # View the result filtered_matrix
What you'll get (matches your expected output):
Col1 Col2 Col3 Col4 row2 2 5 4 0 row3 0 0 8 3
A quick breakdown of how this works:
rowSums(matrix_input > 0): This first creates a boolean matrix where each cell isTRUEif the value is greater than 0, then sums thoseTRUEvalues per row to get a count of positive columns for each row.- The
drop = FALSEargument ensures the result stays a matrix (even if only one row is left, it won't convert to a vector accidentally).
Bonus tweaks if you need them:
- If you ever need to filter for values greater than a different threshold (not 0), just replace
matrix_input > 0withmatrix_input > your_threshold(e.g.,matrix_input > 5). - If your matrix has
NAvalues, addna.rm = TRUEto therowSumscall to ignore them:rowSums(matrix_input > 0, na.rm = TRUE).
内容的提问来源于stack exchange,提问作者Erika
相关产品推荐
相关产品推荐

