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!

2 Answers 2

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

2 Comments

alternatively, apply(m, 1, paste, collapse=" ") to work directly on a matrix.
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\")"
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.