How can two strings be concatenated?

前端 未结 12 1874
时光说笑
时光说笑 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: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 = ", ")) 
    

提交回复
热议问题