Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating columns dynamically in `mutate`

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading