【问题标题】:Concatenate a vector of strings/character连接字符串/字符的向量
【发布时间】:2011-01-07 02:08:05
【问题描述】:

如果我有一个字符类型的向量,我如何将这些值连接成字符串?以下是我将如何使用 paste()

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

屈服"abc"

当然,这只有在我提前知道 sdata 的长度时才有效。

【问题讨论】:

    标签: r string r-faq


    【解决方案1】:

    尝试在粘贴函数中使用空的 collapse 参数:

    paste(sdata, collapse = '')

    感谢http://twitter.com/onelinetips/status/7491806343

    【讨论】:

    • 请注意,如果sdata 可以包含长度相同或可变长度的字符串,则应使用paste(sdata, sep = '', collapse = '') 以避免意外结果。
    【解决方案2】:

    马特的答案绝对是正确的答案。但是,这里有一个用于喜剧救济目的的替代解决方案:

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

    【讨论】:

    • 您真的可以在其中使用 apply() 语句。如果你这样做,我会投票给你;)
    • 如果collapse 参数不存在,这实际上是最优雅的解决方案。所以如果你最近真的不得不做一些非常相似的事情,那么喜剧不会有太大的缓解:)
    【解决方案3】:

    对于sdata

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

    对于整数向量:

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

    【讨论】:

    • 这是一个危险的答案——如果向量的元素中有逗号空格序列,这个答案将删除它们。
    【解决方案4】:

    马特·特纳的答案绝对是正确的答案。但是,本着 Ken Williams 回答的精神,您也可以这样做:

    capture.output(cat(sdata, sep="")) 
    

    【讨论】:

      【解决方案5】:

      您可以像这样使用stri_paste 函数和collapse 参数中的stringi 包:

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

      还有一些基准测试:

      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
      

      【讨论】:

      • 我从未在 R 上执行过基准测试。很高兴学到新东西。
      【解决方案6】:

      这是一个小实用函数,它可以将命名或未命名的值列表折叠为单个字符串,以便于打印。它还将打印代码行本身。来自我的list examples in R 页面。

      生成一些命名或未命名的列表:

      # Define Lists
      ls_num <- list(1,2,3)
      ls_str <- list('1','2','3')
      ls_num_str <- list(1,2,'3')
      
      # Named Lists
      ar_st_names <- c('e1','e2','e3')
      ls_num_str_named <- ls_num_str
      names(ls_num_str_named) <- ar_st_names
      
      # Add Element to Named List
      ls_num_str_named$e4 <- 'this is added'
      

      这是一个将命名或未命名列表转换为字符串的函数:

      ffi_lst2str <- function(ls_list, st_desc, bl_print=TRUE) {
      
        # string desc
        if(missing(st_desc)){
          st_desc <- deparse(substitute(ls_list))
        }
      
        # create string
        st_string_from_list = paste0(paste0(st_desc, ':'), 
                                     paste(names(ls_list), ls_list, sep="=", collapse=";" ))
      
        if (bl_print){
          print(st_string_from_list)
        }
      }
      

      使用之前创建的列表测试函数:

      > ffi_lst2str(ls_num)
      [1] "ls_num:=1;=2;=3"
      > ffi_lst2str(ls_str)
      [1] "ls_str:=1;=2;=3"
      > ffi_lst2str(ls_num_str)
      [1] "ls_num_str:=1;=2;=3"
      > ffi_lst2str(ls_num_str_named)
      [1] "ls_num_str_named:e1=1;e2=2;e3=3;e4=this is added"
      

      用列表元素的子集测试函数:

      > ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
      [1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
      > ffi_lst2str(ls_num[2:3])
      [1] "ls_num[2:3]:=2;=3"
      > ffi_lst2str(ls_str[2:3])
      [1] "ls_str[2:3]:=2;=3"
      > ffi_lst2str(ls_num_str[2:4])
      [1] "ls_num_str[2:4]:=2;=3;=NULL"
      > ffi_lst2str(ls_num_str_named[c('e2','e3','e4')])
      [1] "ls_num_str_named[c(\"e2\", \"e3\", \"e4\")]:e2=2;e3=3;e4=this is added"
      

      【讨论】:

        【解决方案7】:

        另一种方法是使用glue 包:

        glue_collapse(glue("{sdata}"))
        paste(glue("{sdata}"), collapse = '')
        

        【讨论】:

          【解决方案8】:

          stringr 库提供了一些快速的方法来完成此任务。

          str_flatten

          默认情况下会折叠没有空格的字符向量,但也有 collapse 参数:

          str_flatten(sdata)
          [1] "abc"
          

          str_c

          类似于paste,您需要指定collapse 参数来完成此操作:

          str_c(sdata, collapse = "")
          [1] "abc"
          

          base::paste0

          虽然这里与paste 相比没有明显优势,但您可以使用基础 R 中的paste0(sdata, collapse = "")


          更新更长的字符串向量的基准在我的机器上给出了以下结果:

          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 
          

          也本着 Ken Williams 回答的精神:

          Reduce(paste0, sdata)
          [1] "abc"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-07-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-01-12
            相关资源
            最近更新 更多