The library stringr
has a few, fast ways you could accomplish this.
str_flatten
By default will collapse your character vector with no spaces, but does have collapse
argument as well:
str_flatten(sdata)
[1] "abc"
Also has an optional last
argument to use in place of the final separator.
str_c
Similar to paste
with a collapse
argument you need to specify to accomplish this:
str_c(sdata, collapse = "")
[1] "abc"
str_flatten_comma
New as of stringr
1.5.0 if you want a comma delimited collapse. Here the last
argument recognizes the Oxford comma:
str_flatten_comma(sdata)
[1] "a, b, c"
str_flatten_comma(sdata[1:2], last = " and ")
[1] "a and b"
base::paste0
Though there is no obvious advantage here over paste
, you could use paste0(sdata, collapse = "")
from base R.
Updating the benchmark for a much longer string vector gave the following results on my machine:
set.seed(4)
x <- sample(letters, 1E6, replace = T)
microbenchmark(stri_paste(x, collapse=''),
paste(x,collapse=''),
do.call(paste, c(as.list(x), sep="")),
stringr::str_flatten(x),
stringr::str_c(x, collapse = ""),
paste0(x, collapse = ""))
Unit: milliseconds
expr min lq mean median uq max neval cld
stri_paste(x, collapse = "") 21.1788 21.80040 23.45225 22.78430 24.4271 39.1305 100 a
paste(x, collapse = "") 110.7734 114.36595 126.43277 119.02755 136.5902 187.4112 100 b
do.call(paste, c(as.list(x), sep = "")) 538.8329 981.80345 1090.51738 1096.33470 1213.8848 1457.5622 100 c
stringr::str_flatten(x) 20.6276 21.60610 23.36241 22.73915 24.2210 42.3481 100 a
stringr::str_c(x, collapse = "") 20.9274 21.74285 23.75466 22.73950 24.3254 36.6114 100 a
paste0(x, collapse = "") 110.0614 112.81175 124.15555 116.96610 130.6330 168.7199 100 b
Also in the spirit of Ken Williams' answer:
Reduce(paste0, sdata)
[1] "abc"