Alternative function to paste

前端 未结 5 1911
陌清茗
陌清茗 2021-02-04 03:43

Is there a function that can be an alternative to paste ? I would like to know if something like this exists in R:

> buildString ( \"Hi {1}, Have a very nice         


        
5条回答
  •  悲哀的现实
    2021-02-04 03:48

    With version 1.1.0 (CRAN release on 2016-08-19), the stringr package has gained a string interpolation function str_interp().

    With str_interp() the following use cases are possible:

    Variables defined in the environment

    v1 <- "Tom"
    v2 <- "day"
    stringr::str_interp("Hi ${v1}, Have a very nice ${v2} !")
    #[1] "Hi Tom, Have a very nice day !"
    

    Variables provided in a named list as parameter

    stringr::str_interp(
      "Hi ${v1}, Have a very nice ${v2} !",
      list("v1" = "Tom", "v2" = "day"))
    #[1] "Hi Tom, Have a very nice day !"
    

    Variables defined in a vector

    values <- c("Tom", "day")
    stringr::str_interp(
      "Hi ${v1}, Have a very nice ${v2} !",
      setNames(as.list(values), paste0("v", seq_along(values)))
    )
    #[1] "Hi Tom, Have a very nice day !"
    

    Note that the value vector can only hold data of one type (a list is more flexible) and the data are inserted in the order they are provided.

提交回复
热议问题