Home > Software design >  paste multiple columns using a vector containing column names
paste multiple columns using a vector containing column names

Time:06-21

I have a data frame like this:

df <- data.frame(
  a = c("A", "B"),
  b = c("C", "D"),
  c = c("E, F", "G, H"))

> df
  a b    c
1 A C E, F
2 B D G, H

and I want to create a new column like this:

df2 <- data.frame(
  a = c("A", "B"),
  b = c("C", "D"),
  c = c("E, F", "G, H"),
  new = c("A, C: E, F", "B, D: G, H"))

  a b c    new       
1 A C E, F A, C: E, F
2 B D G, H B, D: G, H

I tried this but it's concatenating the two columns as a vector:

cols <- c("a", "b")
single <- "c"

df <- df %>% mutate(
  new = paste0(paste0(df[,cols], collapse = ", "), ": ", df[,single]))

  a b c    new                           
1 A C E, F c("A", "B"), c("C", "D"): E, F
2 B D G, H c("A", "B"), c("C", "D"): G, H

How do I mutate the new column accordingly? Please note, I need to use the 'cols' variable to contain the names of the two columns.

CodePudding user response:

We can use do.call or invoke

library(dplyr)
library(purrr)
df %>% 
   mutate(new = paste(invoke(paste, 
    c(across(all_of(cols)), sep = ", ")), .data[[single]], sep=": "))

-output

 a b    c        new
1 A C E, F A, C: E, F
2 B D G, H B, D: G, H

CodePudding user response:

df$new <- paste0(apply(df[cols], 1, paste, collapse=', '), ': ', df[[single]])
  • Related