Error: argument "no" is missing, with no default

Viewed 435

I am trying to create three new columns that are the appropriate human-readable summary for a diagnosis. For example If diag_1 is <400 then returns "neoplasm". When i try to run the code, I get an error: Problem with mutate() input diagnosis1. x argument "no" is missing, with no default ℹ Input diagnosis1 is ifelse(...).

Here is the code I have:

diabiates %>% 
    mutate(diagnosis1 = ifelse(diag_1 > 140, "infection", 
                               ifelse (diag_1 > 130, "digestive", 
                                       ifelse(diag_1 <20, "neoplasm"))))

                  
  encounter_id diag_1 diag_2 diag_3
1   182795622   428 410 491
2   185569164   428 403 682
3   68184246    428 401 413
4   217930950   415 401 272
5   94628052    648 659 250
6   116653320   414 411 493
7   75331956    730 707 731
8   100954620   428 414 250
9   137518212   427 427 427
10  284406012   715 276 414
11  101488188   403 250 250


1 Answers

We need the no value at the last ifelse. As it is a nested ifelse, the 'yes' value for first ifelse is "infection", and the no is based on the output of second ifelse. Similarly for the second ifelse, the 'no' is from the third ifelse. But, in the last or third ifelse, there is no input for "no". We can specify NA_character_ to fill that

library(dplyr)
diabiates %>% 
    mutate(diagnosis1 = ifelse(diag_1 > 140, "infection", 
                           ifelse (diag_1 > 130, "digestive", 
                              ifelse(diag_1 <20, "neoplasm", 
                  NA_character_))))

Also, instead of nested ifelse, this could be done with case_when in a more readable way

diabiates %>%
    mutate(diagnosis1 = case_when(diag_1 > 140 ~ "infection",
                      diag_1 > 130 & diag_1 <= 140 ~ "digestive",
                      diag_1 < 20 ~ "neoplasm"))

As it is processed sequentially, the second condition can also be diag_1 > 130. But, writing things explicitly makes it easier to understand when we read the same code in the future


Or it can be done using cut or findInterval

diabiates %>%
    mutate(diagnosis1 = cut(diag_1, breaks = c(-Inf, 20,  130, 140),
        labels = c("neoplasm", "digestive", "infection")))
Related