 # Creating multiple ifelse statements will print different results based on the value of percentage

I am trying to create ifelse statements that will print either increased, decreased or remained unchanged if x is >,< or == 0

This is my code:

But I get an error : Error in ifelse(percentage < 0, paste0(" decreased by ", format(round(percentage, : argument "no" is missing, with no default

``````text1 <- paste0("Your value",
ifelse(percentage < 0,
paste0(" decreased by ", format(round(percentage,1), nsmall = 1),
"% in ")),
ifelse(percentage > 0,
paste0(" increased by ", format(round(percentage,1), nsmall = 1),
"% in ")),
ifelse(percentage == 0,
paste0("remained unchanged "), "ERROR"))
``````

The clue is in the error itself. The `no` parameter in `ifelse()` specifies what to do when your condition is `FALSE` and it's missing in one or more of your `ifelse()` calls.

In this case, since you have a total of 3 conditions, you need just 2 `ifelse()` statements. Also, explicitly specifying the `yes` and `no` parameter names will help make your code easier to understand.

``````percentage <- c(-1, 0, 6, -2, 4)

ifelse(percentage < 0,
yes = paste0("decreased by ",
format(round(percentage, 1),
nsmall = 1), "% in "),
no = ifelse(percentage > 0,
yes = paste0("increased by ",
format(round(percentage, 1),
nsmall = 1), "% in "),
no = "remained unchanged")))
#>  "Your value decreased by -1.0% in " "Your value remained unchanged"
#>  "Your value increased by  6.0% in " "Your value decreased by -2.0% in "
#>  "Your value increased by  4.0% in "
``````

Created on 2020-04-02 by the reprex package (v0.3.0)

A `dplyr` way of accomplishing this would be to use `case_when()` which I think makes the code more succinct.

``````library(dplyr, warn.conflicts = FALSE)
#> Warning: package 'dplyr' was built under R version 3.6.3

percentage <- c(-1, 0, 6, -2, 4)

case_when(percentage < 0 ~ paste0("Your value decreased by ",
format(round(percentage, 1), nsmall = 1), "% in "),
percentage > 0 ~ paste0("Your value decreased by ",
format(round(percentage, 1), nsmall = 1), "% in "),
TRUE ~ "Your value remained unchanged")
#>  "Your value decreased by -1.0% in " "Your value remained unchanged"
#>  "Your value decreased by  6.0% in " "Your value decreased by -2.0% in "
#>  "Your value decreased by  4.0% in "
``````

Created on 2020-04-02 by the reprex package (v0.3.0)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.