When using the function dplyr::if_else
, it applies the "else" function on everything which causes a type issue. Is there any way to avoid this? I get the correct results but I really like seeing a clean log in code with no warnings.
library(tibble)
library(magrittr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
# problem that as.numeric is run on case where it isn't a number
tibble(YearOrig=c(as.character(2015:2019), "2017:2019")) %>%
mutate(Year=if_else(YearOrig=="2017:2019", 9999, as.numeric(YearOrig)))
#> Warning in replace_with(out, !condition, false, fmt_args(~false), glue("length
#> of {fmt_args(~condition)}")): NAs introduced by coercion
#> # A tibble: 6 x 2
#> YearOrig Year
#> <chr> <dbl>
#> 1 2015 2015
#> 2 2016 2016
#> 3 2017 2017
#> 4 2018 2018
#> 5 2019 2019
#> 6 2017:2019 9999
# this gives no warning because that case doesn't exist
tibble(YearOrig=c(as.character(2015:2019))) %>%
mutate(Year=if_else(YearOrig=="2017:2019", 9999, as.numeric(YearOrig)))
#> # A tibble: 5 x 2
#> YearOrig Year
#> <chr> <dbl>
#> 1 2015 2015
#> 2 2016 2016
#> 3 2017 2017
#> 4 2018 2018
#> 5 2019 2019
Created on 2020-08-23 by the reprex package (v0.3.0)