R语言多条件求和问题:满足两列大于0时统计对应列值
Hey there! Let's get that sum working correctly for you. The issue with your original code is how you're combining the two conditional filters for rows—R needs a single logical vector to select rows, not separate conditions in the row and column positions.
What Went Wrong
Your code:
sum(DataFrame_a[DataFrame_a[ ,1] > 0, DataFrame_a[ ,2] > 0, 4])
This treats DataFrame_a[ ,2] > 0 as a column index instead of part of the row filter, which is why it didn't work as expected. We need to combine the two conditions into one logical check for each row.
Correct Solutions
1. Base R Approach
Use the logical AND operator (&) to combine your two conditions into a single vector that flags rows where both columns 1 and 2 are greater than 0:
# Calculate sum of column 4 where both column 1 and 2 are > 0 sum(DataFrame_a[DataFrame_a[, 1] > 0 & DataFrame_a[, 2] > 0, 4], na.rm = TRUE)
- The
&ensures we only keep rows where both conditions are true. - Add
na.rm = TRUEto handle any missing values (NA) in your data—without this, if column 4 has NAs, your sum will return NA instead of a number.
2. Tidyverse (dplyr) Approach (More Readable)
If you use the tidyverse ecosystem, this syntax is more intuitive and easier to debug:
library(dplyr) # Replace V1, V2, V4 with your actual column names if needed DataFrame_a %>% filter(V1 > 0, V2 > 0) %>% # Keep rows where both columns meet the condition pull(V4) %>% # Extract the 4th column values sum(na.rm = TRUE) # Sum the extracted values
This breaks down the process step-by-step: filter the rows first, then grab the column you care about, then sum.
Either of these should give you the correct sum of column 4 values for rows where both column 1 and column 2 are greater than 0.
内容的提问来源于stack exchange,提问作者Matthias Herrmann

