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.
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 = "_")
You can try
df %>%
mutate(ID = do.call(paste, c(.[mygroup], sep = "_")))
or
df %>%
mutate(ID = do.call(str_c, c(select(., mygroup), sep = "_")))
which gives
# A tibble: 2 × 4
PERIOD CODE VALUE ID
<dbl> <chr> <dbl> <chr>
1 1995 A 10 1995_A
2 1996 B 20 1996_B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With