2

suppose we have:

mydf <- data.frame(a= LETTERS, b = LETTERS, c =LETTERS)

Now we want to add a new column, containing a concatenation of all columns. So that rows in the new column read "AAA", "BBB", ...

In my mind the following should work?

mydf[,"Concat"] <- apply(mydf, 1, paste0)
akrun
  • 874,273
  • 37
  • 540
  • 662
vanao veneri
  • 970
  • 2
  • 12
  • 31

2 Answers2

4

In addition to @akrun's answer, here is a short explanation on why your code didn't work.
What you are passing to paste0 in your code are vectors and here is the behavior of paste and paste0 with vectors:

> paste0(c("A","A","A"))
[1] "A" "A" "A"

Indeed, to concatenate a vector, you need to use argument collapse:

> paste0(c("A","A","A"), collapse="")
[1] "AAA"

Consequently, your code should have been:

> apply(mydf, 1, paste0, collapse="")
 [1] "AAA" "BBB" "CCC" "DDD" "EEE" "FFF" "GGG" "HHH" "III" "JJJ" "KKK" "LLL" "MMM" "NNN" "OOO" "PPP" "QQQ" "RRR" "SSS" "TTT" "UUU" "VVV"
[23] "WWW" "XXX" "YYY" "ZZZ"
plannapus
  • 18,529
  • 4
  • 72
  • 94
3

We can use do.call with paste0 for faster execution

mydf[, "Concat"] <- do.call(paste0, mydf)
akrun
  • 874,273
  • 37
  • 540
  • 662