串联一个字符串 / 字符的向量
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.
转载于:https://*.com/questions/2098368/concatenate-a-vector-of-strings-character
Try using an empty collapse argument within the paste function:
paste(sdata, collapse = '')
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 = ""))
For sdata
:
gsub(", ","",toString(sdata))
For a vector of integers:
gsub(", ","",toString(c(1:10)))
Matt Turner's answer is definitely the right answer. However, in the spirit of Ken Williams' answer, you could also do:
capture.output(cat(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