rtidyverse

Using vector with strings in mutate with paste


I am trying to build an ID in a tibble with "paste" and a vector with the column names as strings:

library(tidyverse)

df <- tribble(
  ~PERIOD, ~CODE, ~VALUE,
  1995, "A", 10,
  1996, "B", 20
)
df

mygroup <- c("PERIOD", "CODE")

I would like to have this result

# A tibble: 2 x 4
  PERIOD CODE  VALUE ID    
   <dbl> <chr> <dbl> <chr> 
1   1995 A        10 1995_A
2   1996 B        20 1996_B

Of course the following code doesn't do what I want

df %>% 
  mutate(ID = paste(mygroup, collapse = "_"))

as it produces

  PERIOD CODE  VALUE ID         
   <dbl> <chr> <dbl> <chr>      
1   1995 A        10 PERIOD_CODE
2   1996 B        20 PERIOD_CODE

I have tried with !! and curly braces, but nothing worked.


Solution

  • Using base R. The code is concise and tractable but will be inefficient if mygroup is very long. Use do.call() instead.

    df$ID <- Reduce(\(x, y) paste(x, y, sep = "_"), df[mygroup])
    
    #   PERIOD CODE  VALUE ID    
    #    <dbl> <chr> <dbl> <chr> 
    # 1   1995 A        10 1995_A
    # 2   1996 B        20 1996_B
    

    Another concise but inefficient solution:

    df$ID <- apply(df[mygroup], 1, paste, collapse = "_")