9

I have an arbitrary number of columns containing text data that have been assembled using the cbind() command, for example:

[1,] "Text 1,1" "Text 1,2" "Text 1,n"
[2,] "Text 2,1" "Text 2,2" "Text 2,n"
[3,] "Text 3,1" "Text 3,2" "Text 3,n"
[n,] "Text n,1" "Text n,2" "Text n,n"

I want to concatenate each row together, so I'm left with:

[1,] "Text 1,1 Text 1,2 Text 1,n"
[n,] "Text n,1 Text n,2 Text n,n"

Currently, I'm doing this using a for loop (where textColumns is the cbind() matrix):

concatColumn <- c()
for (i in 1:ncol(textColumns)) concatColumn <- paste(concatColumn,textColumns[,i])

Is there a simpler, more elegant way to do this in R? I've been looking around for ways to do this using the paste() command without a for loop, but haven't been able to find a solution. Thank you in advance for your help!

Timothy P. Jurka
  • 918
  • 1
  • 11
  • 21

2 Answers2

24

It's easy with a data.frame,

m = matrix(letters[1:12], 3, byrow=TRUE)
do.call(paste, as.data.frame(m, stringsAsFactors=FALSE))
#[1] "a b c d" "e f g h" "i j k l"
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • 5
    alternatively, `apply(m, 1, paste, collapse=" ")` to work directly on a matrix. – baptiste Dec 28 '11 at 21:42
  • That's what I was looking for. The apply() method works beautifully. Thank you! The converting to data.frame method gave me some weird output: `[1] "c(\"t1\", \"t2\", \"t3\")" "c(\"t4\", \"t5\", \"t6\")" "c(\"t7\", \"t8\", \"t9\")"` – Timothy P. Jurka Dec 28 '11 at 21:45
8

Just use paste with its collapse argument:

R> row <- c("Text 1,1",  "Text 1,2", "Text 1,n")
R> paste(row, collapse=" ")
[1] "Text 1,1 Text 1,2 Text 1,n"
R> 

paste is vectorised, so you can feed it multiple arguments at once.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Hi Dirk, thanks for the reply. However, when dealing with multiple columns that method concatenates them all together into one character vector. For example `cols <- cbind(c("1","2","3"),c("4","5","6"),c("7","8","9"))` yields one character vector of `[1] "1" "2" "3" "4" "5" "6" "7" "8" "9"`, whereas I need three rows with `[1] "1 4 7"` `[2] "2 5 8"` etc. – Timothy P. Jurka Dec 28 '11 at 21:37