Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using vector with strings in mutate with paste [duplicate]

Tags:

r

tidyverse

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.

like image 628
arnyeinstein Avatar asked Nov 07 '25 06:11

arnyeinstein


2 Answers

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 = "_")
like image 123
sindri_baldur Avatar answered Nov 09 '25 08:11

sindri_baldur


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
like image 45
ThomasIsCoding Avatar answered Nov 09 '25 10:11

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!