Error using if() in mutate() in R 4.4.0

I updated R to it's new version 4.4.0 and I'm finding errors which I didn't had

for example, this used to work:

temp <- data.frame("a"=c(1,2),"b"=c(3,4),"c"=0)

temp <- temp %>% mutate(c=if(a>b){100}else{200})

the c column would update to 200 in every line. but now I got this error
image

So, what's the new correct way to do an update with a condition?

The help on if says the condition must be of length one. I don't think that has changed, but I could be wrong.

Is it possible that you want if_else?

1 Like

Add rowwise()?

temp <- temp %>% rowwise() %>% mutate(c=if(a>b){100}else{200})

In older versions of R if(...) with ... longer than 1 was tolerated, but only the first value was taken into account. So your code was probably not doing what you wanted. For example, using R4.1.3 (on Posit Cloud):

temp <- data.frame(a = c(1,3),
                   b = c(2,2))

temp |>
    dplyr::mutate(c = if(a>b){100}else{200})
#> Warning: There was 1 warning in `dplyr::mutate()`.
#> ℹ In argument: `c = if (...) NULL`.
#> Caused by warning in `if (a > b) ...`:
#> ! the condition has length > 1 and only the first element will be used
#>   a b   c
#> 1 1 2 200
#> 2 3 2 200

As you can see, since R 1.7.0 it gave a warning, since R 4.2.0, it gives an error, since it's probably not what you want to do.

What you need is then, either make explicit that you're only considering the first value:

temp |>
  mutate(c = if(a[[1]]>b[[1]]){100}else{200})
#>   a b   c
#> 1 1 2 200
#> 2 3 2 200

Or, as suggested by startz, use if_else() for a vectorized version of if/else:

temp |>
  mutate(c = if_else(a > b, 100, 200))
#>   a b   c
#> 1 1 2 200
#> 2 3 2 100
1 Like

thank you, you and everyone.
funny thing that I began with if_else but for some reason it didn't like it back then. I guess I must return to that.

also the rowwise worked

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.