Dimitris Raidos
Dimitris Raidos

Reputation: 33

How to concatenate one string column with multiple string columns in R

I'm trying to concatenate the values in the data frame (df1) below row-wise, and get the result of (df2).

# Input
df1 <- data.frame (first_column  = c("A", "B", "C", "D"),
                  second_column = c("var1", "var2", "var3", "var4"),
                  third_column  = c("var5", "var6", "var7", " "),
                  fourth_column = c("var8", "var9", " ", " "))
# Ouput
df2 <- data.frame (first_column = c("A var1", "B var2", "B var3", "B var4"),
                  second_column  = c("A var5", "B var6", "B var7", "B "),
                  thrid_column = c("A var8", "B var9", "B ", "B "))

My best result so far was with the following code, but not what I wanted:

# Get the number of columns as df1 will differ in size from time to time,
and the only thing I'd like to change to the script is the file path for df1.

nc <- ncol(df1)
 
df2 <- data.frame(paste(df1$first_column, df1[,c(2:nc)]))

Any 💭 ideas and feedback would be much appreciated. 😁

Upvotes: 3

Views: 39

Answers (1)

akrun
akrun

Reputation: 886938

We may loop across the columns from 'second_column' to the last, paste (str_c) the first_column with the column values and rename the columns

library(dplyr)
library(stringr)
df1 %>% 
  transmute(across(second_column:last_col(), 
   ~ str_c(first_column, .x, sep = ' '))) %>%
  rename_with(~ names(df1)[-length(.x)])

-or using base R

df2 <- df1
df2[-ncol(df1)] <- lapply(df1[-1], \(x) paste(df1$first_column, x))
df2 <- df2[-ncol(df2)]

Upvotes: 2

Related Questions