Home > Software design >  Creating columns dynamically in `mutate`
Creating columns dynamically in `mutate`

Time:09-28

Consider the following dataset:

library(tidyverse)

tbl <- tibble(
  x = letters[1:3],
  y = c("a", "a", "b"),
  z = letters[4:6]
)

I'd like to create a function to create new columns containing unique ids for each value of a given set of columns, with a single mutate call.

I tried the following but I'm getting an error:

add_ids <- function(.data, ...) {
  mutate(.data, map_chr(c(...), ~ {
    "{.x}_id" := vctrs::vec_group_id(.data[[.x]])
  }))
}

add_ids(tbl, x, y)

Expected output:

# A tibble: 3 × 5
  x     y     z      x_id  y_id
  <chr> <chr> <chr> <int> <int>
1 a     a     d         1     1
2 b     a     e         2     1
3 c     b     f         3     2

CodePudding user response:

You could rather use across in this case:

add_ids <- function(.data, var) {
  mutate(.data, 
         across({{ var }}, vctrs::vec_group_id, .names = "{col}_id"))

}

add_ids(tbl, c(x, y))
## A tibble: 3 × 5
#  x     y     z      x_id  y_id
#  <chr> <chr> <chr> <int> <int>
#1 a     a     d         1     1
#2 b     a     e         2     1
#3 c     b     f         3     2
  • Related