How can two strings be concatenated?

前端 未结 12 1869
时光说笑
时光说笑 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:19

    As others have pointed out, paste() is the way to go. But it can get annoying to have to type paste(str1, str2, str3, sep='') everytime you want the non-default separator.

    You can very easily create wrapper functions that make life much simpler. For instance, if you find yourself concatenating strings with no separator really often, you can do:

    p <- function(..., sep='') {
        paste(..., sep=sep, collapse=sep)
    }
    

    or if you often want to join strings from a vector (like implode() from PHP):

    implode <- function(..., sep='') {
         paste(..., collapse=sep)
    }
    

    Allows you do do this:

    p('a', 'b', 'c')
    #[1] "abc"
    vec <- c('a', 'b', 'c')
    implode(vec)
    #[1] "abc"
    implode(vec, sep=', ')
    #[1] "a, b, c"
    

    Also, there is the built-in paste0, which does the same thing as my implode, but without allowing custom separators. It's slightly more efficient than paste().

提交回复
热议问题