Search code examples
rgroup-bycase-when

group_by table and change the values if the sum of the column is 0 to NA in R


I have a table and group it by two columns. In each of this groups I want to change several columns. If the sum of a column (in the group) is 0, then each row in this column should be changed to NA. In the end I want the starting table, but with NA instead of 0.

I tried:

table_neu <- table %>%
    group_by(A,B) %>%
    mutate_at(.vars = vars(C_01:C_12),
              .funs = funs(case_when(
                  sum(.) == 0 ~ NA,
                  TRUE ~ .)),
              na.rm = TRUE) %>%
    ungroup()

I get this error and don't know what's the problem.

Case 3 (colsum(C_01) == 0 ~ NA) must be a two-sided formula, not a logical vectorTraceback:


Solution

  • Try using :

    library(dplyr)
    
    table_neu <- table %>%
                   group_by(A,B) %>%
                   mutate_at(vars(C_01:C_12),~case_when(
                                               sum(., na.rm = TRUE) == 0 ~ NA_real_,
                                               TRUE ~ .)) %>%
                    ungroup()