How can two strings be concatenated?

前端 未结 12 1784
时光说笑
时光说笑 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().

    0 讨论(0)
  • 2020-11-22 16:19

    Another way:

    sprintf("%s you can add other static strings here %s",string1,string2)
    

    It sometimes useful than paste() function. %s denotes the place where the subjective strings will be included.

    Note that this will come in handy as you try to build a path:

    sprintf("/%s", paste("this", "is", "a", "path", sep="/"))
    

    output

    /this/is/a/path
    
    0 讨论(0)
  • 2020-11-22 16:19

    Another non-paste answer:

    x <- capture.output(cat(data, sep = ","))
    x
    [1] "GAD,AB"
    

    Where

     data <- c("GAD", "AB")
    
    0 讨论(0)
  • 2020-11-22 16:29

    help.search() is a handy function, e.g.

    > help.search("concatenate")
    

    will lead you to paste().

    0 讨论(0)
  • 2020-11-22 16:29

    Alternatively, if your objective is to output directly to a file or stdout, you can use cat:

    cat(s1, s2, sep=", ")
    
    0 讨论(0)
  • 2020-11-22 16:31

    Consider the case where the strings are columns and the result should be a new column:

    df <- data.frame(a = letters[1:5], b = LETTERS[1:5], c = 1:5)
    
    df$new_col <- do.call(paste, c(df[c("a", "b")], sep = ", ")) 
    df
    #  a b c new_col
    #1 a A 1    a, A
    #2 b B 2    b, B
    #3 c C 3    c, C
    #4 d D 4    d, D
    #5 e E 5    e, E
    

    Optionally, skip the [c("a", "b")] subsetting if all columns needs to be pasted.

    # you can also try str_c from stringr package as mentioned by other users too!
    do.call(str_c, c(df[c("a", "b")], sep = ", ")) 
    
    0 讨论(0)
提交回复
热议问题