Way to correctly do a dplyr call a column within ifelse

df |>
    mutate(a = b)

Generally, dplyr would recognise that a and b are column names within df. However, when using ifelse(), it would not work.

df |>
    mutate(a = ifelse(b > 1, 1, 0))

Is there a way to make this work?

set.seed(1)

df <- data.frame(b = sample(0:2,5, replace = TRUE),
                 a = sample(1:10,5, replace = TRUE )
)

df
#>   b a
#> 1 0 7
#> 2 2 2
#> 3 0 3
#> 4 1 1
#> 5 0 5

df |>
  dplyr::mutate(a = ifelse(b > 1, 1, 0))
#>   b a
#> 1 0 0
#> 2 2 1
#> 3 0 0
#> 4 1 0
#> 5 0 0

Created on 2022-02-24 by the reprex package (v2.0.0)

Hi there, as you can see it is working? So I am not sure what you are doing differently in your example then.

1 Like

The new pipe character was only introduced in 4.1. You will have to make use of the older pipe instead then.

This topic was automatically closed 7 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.