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)
1
  • 1
    With the apply logic. mydf["concat"] <- apply(mydf, 1, paste0, collapse = "") Commented Nov 22, 2016 at 10:37

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

Comments

3

We can use do.call with paste0 for faster execution

mydf[, "Concat"] <- do.call(paste0, mydf)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.