1

I'm trying to merge several hundred columns of a dataframe. Currently trying to do this with a for loop, which isn't working.

The columns are numbered 1 : n, lets say 512.

for(i in 1:512) {
    DF[as.numeric(i)] <-paste(DF[as.numeric(i)], DF[as.numeric(i)+1])  
}

(using the "as.numeric(i)" since I was getting errors when trying to select the next column)

EDIT

All the values are strings, with many rows not being filled till the 512 columns. I'm trying to combine all the strings in 1 row into a single string.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jan Lerch
  • 13
  • 4
  • 1
    You can use `apply(df, 1, paste0, collapse ="")` – MKR Mar 31 '18 at 16:04
  • it would be better if you can provide reproducible example. Have a look at https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – MKR Mar 31 '18 at 16:05

1 Answers1

1

You can try apply with paste0 as:

df <- data.frame(id = 1:10, name = rep(c("Test1", "Test2"),5), 
                 value = 101:110, stringsAsFactors = FALSE)

apply(df, 1, paste0, collapse ="")

#Result
# [1] " 1Test1101" " 2Test2102" " 3Test1103" " 4Test2104" " 5Test1105" " 6Test2106"
# [7] " 7Test1107" " 8Test2108" " 9Test1109" "10Test2110"
MKR
  • 19,739
  • 4
  • 23
  • 33