Home > Blockchain >  How to concatenate one string column with multiple string columns in R
How to concatenate one string column with multiple string columns in R

Time:10-24

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

  • Related