~Onlooker
2010-01-20 01:00
采纳率: 0%
浏览 235

串联一个字符串 / 字符的向量

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://stackoverflow.com/questions/2098368/concatenate-a-vector-of-strings-character

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • 叼花硬汉 2010-01-20 01:21
    已采纳

    Try using an empty collapse argument within the paste function:

    paste(sdata, collapse = '')

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

    点赞 打赏 评论
  • elliott.david 2010-01-20 17:28

    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 = ""))
    
    点赞 打赏 评论
  • python小菜 2013-11-15 15:21

    For sdata:

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

    For a vector of integers:

    gsub(", ","",toString(c(1:10)))
    
    点赞 打赏 评论
  • Lotus@ 2016-03-18 21:00

    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="")) 
    
    点赞 打赏 评论
  • MAO-EYE 2017-08-17 14:02

    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
    
    点赞 打赏 评论

相关推荐 更多相似问题