vanao veneri vanao veneri - 13 days ago 5
R Question

How do I paste string columns in data.frame

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)

Answer

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"
Comments