Home > Software design >  How exclude the rows that have values = 0
How exclude the rows that have values = 0

Time:12-11

What code I can used to exclude the rows that have GR = 0 in my database, before doing the rowSums calculation?

library(dplyr)

Test <- structure(list(date2 = structure(c(18808, 18808, 18809, 18810
), class = "Date"), Category = c("FDE", "ABC", "FDE", "ABC"), 
GR = c(0, 1, 0, 1),
coef1 = c(445.23231, 1.31231, 6.32323, 1.232),coef2 = c(8.3231, 3.3432, 1.3233, 6.3233)), 
row.names = c(NA, 4L), class = "data.frame")
> Test
       date2 Category GR     coef1  coef2
1 2021-06-30      FDE  0 445.23231 8.3231
2 2021-06-30      ABC  1   1.31231 3.3432
3 2021-07-01      FDE  0   6.32323 1.3233
4 2021-07-02      ABC  1   1.23200 6.3233
Test %>%
  mutate(sum = rowSums(across(3:last_col()), na.rm = TRUE), 
         across(where(is.numeric), ~sprintf("US $%.2f", .x)))

CodePudding user response:

Does this work:

library(dplyr)
Test %>% filter(GR != 0)
       date2 Category GR   coef1  coef2
1 2021-06-30      ABC  1 1.31231 3.3432
2 2021-07-02      ABC  1 1.23200 6.3233

Overall code:

Test %>% filter(GR != 0) %>% mutate(sum = rowSums(across(3:last_col()), na.rm = TRUE), 
                                    across(where(is.numeric), ~sprintf("US $%.2f", .x)))
       date2 Category       GR    coef1    coef2      sum
1 2021-06-30      ABC US $1.00 US $1.31 US $3.34 US $5.66
2 2021-07-02      ABC US $1.00 US $1.23 US $6.32 US $8.56
  •  Tags:  
  • r
  • Related