Dynamic Column Naming with a Loop

Peng Chen

March 15, 2021

How do you transform dataset t1

t1
## # A tibble: 10 x 1
##     food
##    <int>
##  1     3
##  2     3
##  3    10
##  4     2
##  5     6
##  6     5
##  7     4
##  8     6
##  9     9
## 10    10

to dataset t2?

t2
## # A tibble: 10 x 11
##     food food_1 food_2 food_3 food_4 food_5 food_6 food_7 food_8 food_9 food_10
##    <int>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>   <dbl>
##  1     3      0      0      1      0      0      0      0      0      0       0
##  2     3      0      0      1      0      0      0      0      0      0       0
##  3    10      0      0      0      0      0      0      0      0      0       1
##  4     2      0      1      0      0      0      0      0      0      0       0
##  5     6      0      0      0      0      0      1      0      0      0       0
##  6     5      0      0      0      0      1      0      0      0      0       0
##  7     4      0      0      0      1      0      0      0      0      0       0
##  8     6      0      0      0      0      0      1      0      0      0       0
##  9     9      0      0      0      0      0      0      0      0      1       0
## 10    10      0      0      0      0      0      0      0      0      0       1

One way is the following:

my_fun <- function(.data) {
  for(i in 1:10) 
    .data <- .data %>% mutate("food_{i}" := case_when(food == i ~ 1, TRUE ~ 0))
  .data
}

t2 <- my_fun(t1)

In the mutate() function, notice the use of glue-like grammar

"food_{i}"

on the left and the := symbol in the middle.