Join N columns of text in R

I have an arbitrary number of columns containing text data that were collected 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 combine each row together, so I have to:

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

I am currently doing this with a for loop (where textColumns is the cbind () matrix):

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

Is there an easier and more elegant way to do this in R? I was looking for ways to do this using the paste () command without a for loop, but could not find a solution. Thank you in advance for your help!

+7
source share
2 answers

Easy with data.frame,

 m = matrix(letters[1:12], 3, byrow=TRUE) do.call(paste, as.data.frame(m, stringsAsFactors=FALSE)) #[1] "abcd" "efgh" "ijkl" 
+19
source

Just use paste with the 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 vectorized, so you can pass multiple arguments at once.

+7
source

All Articles