Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string as variable on LHS and in mutate command

Tags:

r

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

like image 877
arnyeinstein Avatar asked Jun 12 '26 14:06

arnyeinstein


1 Answers

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(....

like image 199
zephryl Avatar answered Jun 14 '26 05:06

zephryl