nicholas
nicholas

Reputation: 983

Dynamically assign column names on right-hand side of := operator

This answer indicates how to dynamically assign column names for the variable on the left side of the := operator, but I can't get it to work for assignment on the right side of the operator. The following toy example illustrates what I'm trying to accomplish:

library(tidyverse)

df <- tribble(
  ~geo, ~type, ~a_b_avg, ~bperPerson,
  "a",  "b",   3,        2,
  "a",  "b",   3,        4
)

f15 <- function(.data, geo, type) {
  df %>% 
  mutate("{{geo}}_{{type}}_15" :=  if_else("{{type}}perPerson" <
                                             "{{geo}}_{{type}}_avg",
                                           1, 
                                           0))
}

f15(df, "a", "b")

I would like to end up with a new column, a_b_15, which equals 1 in the first row (where bperPerson < a_b_avg) and 0 in the second row (where bperPerson > a_b_avg). Instead, I get the column `"a"_"b"_15`, with both values equal to zero.

Upvotes: 1

Views: 331

Answers (1)

akrun
akrun

Reputation: 887088

Regarding the evaluation within if_else, can create the string column name in paste, convert to symbol and evaluate (!!)

library(dplyr)
f15 <- function(.data, geo, type) {
   df %>% 
    mutate(!!paste0(geo, "_", type, "_15") :=
      if_else(!! rlang::sym(paste0(type, "perPerson")) <
                           !!rlang::sym(paste0(geo, "_", type, "_avg")),
                                            1, 
                                            0))
}

-output

> f15(df, "a", "b")
# A tibble: 2 x 5
  geo   type  a_b_avg bperPerson a_b_15
  <chr> <chr>   <dbl>      <dbl>  <dbl>
1 a     b           3          2      1
2 a     b           3          4      0

Upvotes: 1

Related Questions