Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating N columns of text in R

Tags:

r

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!

like image 538
Timothy P. Jurka Avatar asked Dec 28 '11 21:12

Timothy P. Jurka


People also ask

How do I concatenate multiple columns in R?

How do I concatenate two columns in R? To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.

How do I combine all columns into one column in R?

To convert multiple columns into single column in an R data frame, we can use unlist function. For example, if we have data frame defined as df and contains four columns then the columns of df can be converted into a single by using data. frame(x=unlist(df)).

How do I concatenate data in R?

To concatenate strings in r programming, use paste() function. The syntax of paste() function that is used to concatenate two or more strings.


2 Answers

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"
like image 115
baptiste Avatar answered Oct 30 '22 18:10

baptiste


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.

like image 33
Dirk Eddelbuettel Avatar answered Oct 30 '22 18:10

Dirk Eddelbuettel