How can two strings be concatenated?

前端 未结 12 1879
时光说笑
时光说笑 2020-11-22 16:14

How can I concatenate (merge, combine) two values? For example I have:

tmp = cbind(\"GAD\", \"AB\")
tmp
#      [,1]  [,2]
# [1,] \"GAD\" \"AB\"
12条回答
  •  执笔经年
    2020-11-22 16:46

    For the first non-paste() answer, we can look at stringr::str_c() (and then toString() below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.

    Very simple to use, as you can see.

    tmp <- cbind("GAD", "AB")
    library(stringr)
    str_c(tmp, collapse = ",")
    # [1] "GAD,AB"
    

    From its documentation file description, it fits this problem nicely.

    To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.

    Added 4/13/2016: It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString() is basically a version of paste() with collapse = ", " hard-coded, so you can do

    toString(tmp)
    # [1] "GAD, AB"
    

提交回复
热议问题