Concatenate a vector of strings/character

If I have a vector of type character, how can I concatenate the values into string? Here's how I would do it with paste():

sdata = c('a', 'b', 'c')
paste(sdata[1], sdata[2], sdata[3], sep ='')

yielding "abc".

But of course, that only works if I know the length of sdata ahead of time.


Try using an empty collapse argument within the paste function:

paste(sdata, collapse = '')

Thanks to http://twitter.com/onelinetips/status/7491806343


Matt's answer is definitely the right answer. However, here's an alternative solution for comic relief purposes:

do.call(paste, c(as.list(sdata), sep = ""))

You can use stri_paste function with collapse parameter from stringi package like this:

stri_paste(letters, collapse='')
## [1] "abcdefghijklmnopqrstuvwxyz" 

And some benchmarks:

require(microbenchmark)
test <- stri_rand_lipsum(100)
microbenchmark(stri_paste(test, collapse=''), paste(test,collapse=''), do.call(paste, c(as.list(test), sep="")))
Unit: microseconds
                                      expr     min       lq     mean   median       uq     max neval
           stri_paste(test, collapse = "") 137.477 139.6040 155.8157 148.5810 163.5375 226.171   100
                paste(test, collapse = "") 404.139 406.4100 446.0270 432.3250 442.9825 723.793   100
do.call(paste, c(as.list(test), sep = "")) 216.937 226.0265 251.6779 237.3945 264.8935 405.989   100

For sdata:

gsub(", ","",toString(sdata))

For a vector of integers:

gsub(", ","",toString(c(1:10)))