csdnceshi80
胖鸭
2011-08-26 07:25

如何连接两个字符串?

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

tmp = cbind("GAD", "AB")
tmp
#      [,1]  [,2]
# [1,] "GAD" "AB"

My goal is to concatenate the two values in "tmp" to one string:

tmp_new = "GAD,AB"

Which function can do this for me?

转载于:https://stackoverflow.com/questions/7201341/how-can-two-strings-be-concatenated

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

11条回答

  • csdnceshi58 Didn"t forge 10年前
    paste()
    

    is the way to go. As the previous posters pointed out, paste can do two things:

    concatenate values into one "string", e.g.

    > paste("Hello", "world", sep=" ")
    [1] "Hello world"
    

    where the argument sep specifies the character(s) to be used between the arguments to concatenate, or collapse character vectors

    > x <- c("Hello", "World")
    > x
    [1] "Hello" "World"
    > paste(x, collapse="--")
    [1] "Hello--World"
    

    where the argument collapse specifies the character(s) to be used between the elements of the vector to be collapsed.

    You can even combine both:

    > paste(x, "and some more", sep="|-|", collapse="--")
    [1] "Hello|-|and some more--World|-|and some more"
    

    Hope this helps.

    点赞 22 评论 复制链接分享
  • csdnceshi70 笑故挽风 7年前

    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().

    点赞 10 评论 复制链接分享
  • csdnceshi60 ℡Wang Yan 10年前

    Given the matrix, tmp, that you created:

    paste(tmp[1,], collapse = ",")
    

    I assume there is some reason why you're creating a matrix using cbind, as opposed to simply:

    tmp <- "GAD,AB"
    
    点赞 10 评论 复制链接分享
  • csdnceshi52 妄徒之命 5年前

    You can create you own operator :

    '%&%' <- function(x, y)paste0(x,y)
    "new" %&% "operator"
    [1] newoperator`
    

    You can also redefine 'and' (&) operator :

    '&' <- function(x, y)paste0(x,y)
    "dirty" & "trick"
    "dirtytrick"
    

    messing with baseline syntax is ugly, but so is using paste()/paste0() if you work only with your own code you can (almost always) replace logical & and operator with * and do multiplication of logical values instead of using logical 'and &'

    点赞 9 评论 复制链接分享
  • weixin_41568196 撒拉嘿哟木头 10年前
    > tmp = paste("GAD", "AB", sep = ",")
    > tmp
    [1] "GAD,AB"
    

    I found this from Google by searching for R concatenate strings: http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html

    点赞 9 评论 复制链接分享
  • csdnceshi74 7*4 6年前

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

    cat(s1, s2, sep=", ")
    
    点赞 7 评论 复制链接分享
  • weixin_41568208 北城已荒凉 4年前

    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 = ", ")) 
    
    点赞 7 评论 复制链接分享
  • csdnceshi74 7*4 5年前

    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
    
    点赞 7 评论 复制链接分享
  • csdnceshi67 bug^君 7年前

    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"
    
    点赞 5 评论 复制链接分享
  • csdnceshi78 程序go 10年前

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

    > help.search("concatenate")
    

    will lead you to paste().

    点赞 5 评论 复制链接分享
  • csdnceshi58 Didn"t forge 3年前

    Another non-paste answer:

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

    Where

     data <- c("GAD", "AB")
    
    点赞 评论 复制链接分享