I have the following function which works fine, but I am not sure if this is the actual way to do it as programming with tidyverse changed over the last year(s). I am especially interested in using a more consistent way of using strings on the LHS and RHS. In my example, there are three ways at the moment: !!, {{}} and !!as.name().
noga_data <- tibble(NOGA = c("01", "02", "03", "05"))
assign_noga_class <- function(mydata, noga2, noga_class) {
mydata %>%
mutate(!!noga_class := ifelse(as.numeric({{ noga2 }} ) %in% c(1:3), 1, NA)) %>%
mutate(!!noga_class := ifelse(as.numeric({{ noga2 }}) %in% c(5:34), 2, !!as.name(noga_class)))
}
assign_noga_class(noga_data, NOGA, "NOGA_CLASS")
I thought that the bang-bang notation was outdated/superseded by something else. I like to know because I am using this as an example for a group I would like to teach about programming in R. Any hints on blogs or other web pages are also very welcome.
Cheers
Renger
I don’t think !! is deprecated, but you can now use glue syntax to interpolate variable names (docs):
library(dplyr)
assign_noga_class <- function(mydata, noga2, noga_class) {
mydata %>%
mutate("{noga_class}" := ifelse(as.numeric({{ noga2 }} ) %in% c(1:3), 1, NA)) %>%
mutate("{noga_class}" := ifelse(as.numeric({{ noga2 }}) %in% c(5:34), 2, !!as.name(noga_class)))
}
assign_noga_class(noga_data, NOGA, "NOGA_CLASS")
# A tibble: 4 × 2
NOGA NOGA_CLASS
<chr> <dbl>
1 01 1
2 02 1
3 03 1
4 05 2
This can be handy if you want to add to the passed variable name, e.g.,
assign_noga_class <- function(mydata, noga2, noga_class) {
mydata %>%
mutate("{noga_class}" := ifelse(as.numeric({{ noga2 }} ) %in% c(1:3), 1, NA)) %>%
mutate("{noga_class}_v2" := ifelse(as.numeric({{ noga2 }}) %in% c(5:34), 2, !!as.name(noga_class)))
}
assign_noga_class(noga_data, NOGA, "NOGA_CLASS")
# A tibble: 4 × 3
NOGA NOGA_CLASS NOGA_CLASS_v2
<chr> <dbl> <dbl>
1 01 1 1
2 02 1 1
3 03 1 1
4 05 NA 2
Finally, as @Jean-ClaudeArbaut points out, you can also use {{: e.g., mutate({{noga_class}} := ifelse(....
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