Conditional sum with NAs

Viewed 36

I have a following dataframe.

id color grade
1 green B
2 red
3 C
4
5 blue A

I have to add columns named col_scr and grd_scr based on color and grade. Then I have to add those two columns to get a column named final_score. My desired dataframe should look like as follow,

id color grade col_scr grd_scr final_score
1 green B 1 1 3
2 red 3 NA 3
3 C NA 0 0
4 NA NA NA
5 blue A 2 2 4

My code so far looks like,

df <- df %>%
   mutate(col_scr = case_when(color == 'green' ~ 1,
                              color == 'blue' ~ 2,
                              color == 'red' ~ 3),
          grd_scr = case_when(grade == 'A' ~ 2,
                              grade == 'B' ~ 1,
                              grade == 'C' ~ 0))

How to add my 3rd column final_score into mutate?

1 Answers

You can use an ifelse condition to sum only if both variable are not NAs, otherwise NA (credits to @Darren Tsai for the if_all part).

df %>% 
  mutate(final_score = ifelse(if_all(col_csr:grd_scr, is.na), 
                              NA, rowSums(across(col_scr:grd_scr), na.rm = T)))
Related