How can two strings be concatenated?

前端 未结 12 1875
时光说笑
时光说笑 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 16:39

    glue is a new function, data class, and package that has been developed as part of the tidyverse, with a lot of extended functionality. It combines features from paste, sprintf, and the previous other answers.

    tmp <- tibble::tibble(firststring = "GAD", secondstring = "AB")
    (tmp_new <- glue::glue_data(tmp, "{firststring},{secondstring}"))
    #> GAD,AB
    

    Created on 2019-03-06 by the reprex package (v0.2.1)

    Yes, it's overkill for the simple example in this question, but powerful for many situations. (see https://glue.tidyverse.org/)

    Quick example compared to paste with with below. The glue code was a bit easier to type and looks a bit easier to read.

    tmp <- tibble::tibble(firststring = c("GAD", "GAD2", "GAD3"), secondstring = c("AB1", "AB2", "AB3"))
    (tmp_new <- glue::glue_data(tmp, "{firststring} and {secondstring} went to the park for a walk. {firststring} forgot his keys."))
    #> GAD and AB1 went to the park for a walk. GAD forgot his keys.
    #> GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys.
    #> GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys.
    (with(tmp, paste(firststring, "and", secondstring, "went to the park for a walk.", firststring, "forgot his keys.")))
    #> [1] "GAD and AB1 went to the park for a walk. GAD forgot his keys."  
    #> [2] "GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys."
    #> [3] "GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys."
    

    Created on 2019-03-06 by the reprex package (v0.2.1)

提交回复
热议问题