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!
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>.
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)).
To concatenate strings in r programming, use paste() function. The syntax of paste() function that is used to concatenate two or more strings.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With