I wish to apply one of two functions to elements of vector. Choice of which function to use is made based on vector's values.
To be specific: imagine you want to convert years coded with two digits (like '07' for '2007' and '85' for '1985') to four digits, assuming that all the dates are between 1919 and 2018.
So, you have to add 1900 to numbers larger than 18 and add 2000 to other numbers.
Now I want to do that with %>%
operator (to be able to use it inside mutate
statment in future).
This one:
c(18,20,21,15) %>% ifelse(.>18, .+1900, .+2000)
produces an error:
Error in ifelse(., . > 18, . + 1900, . + 2000) : unused argument (. + 2000)
I even understand why: %>%
forces vector c(18,20,21,15)
to be used as first argument of ifelse
.
I have a workaround using anonymous function:
c(18,20,21,15) %>% (function(x) ifelse(x>18, x+1900, x+2000))
[1] 2018 1920 1921 2015
Can you suggest anything to avoid them (them = anonymous functions)?
Your solution works fine if you add curly braces:
c(18,20,21,15) %>% {ifelse(.>18, .+1900, .+2000)}
# [1] 2018 1920 1921 2015
You could also do this to avoid the {}
:
c(18,20,21,15) %>% `+`(1900+100*(.<=18))
Or with magrittr
:
library(magrittr)
c(18,20,21,15) %>% add(1900+100*(.<=18))
keeping your ifelse
:
c(18,20,21,15) %>% add(ifelse(.>18,1900,2000))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With