代码之家  ›  专栏  ›  技术社区  ›  tfcoe

用相同的值替换Sprintf中的多个变量

  •  8
  • tfcoe  · 技术社区  · 7 年前

    我希望在R中的字符串中插入一个已定义的变量,该变量将被插入到多个位置。

    我看到了 sprintf 可能有用。

    所需输入示例:

    a <- "tree"
    b <- sprintf("The %s is large but %s is small. %s", a) 
    

    理想输出将返回

    "The tree is large but tree is small. tree"
    

    我知道我可以使用如下功能:

    b <- sprintf("The %s is large but %s is small. %s",a,a,a)
    

    然而,对于我的实际工作,我需要插入10次以上,因此我正在寻找一种更干净/更简单的解决方案。

    gsub是更好的解决方案吗?

    我的确切问题已经在这里得到了回答,但它是针对语言的:

    Replace all variables in Sprintf with same variable

    3 回复  |  直到 7 年前
        1
  •  14
  •   s_baldur    6 年前

    下面是一个实际的sprintf()解决方案:

    a <- "tree"
    sprintf("The %1$s is large but %1$s is small. %1$s", a)
    [1] "The tree is large but tree is small. tree"
    

    官方sprintf()文档中有更多示例。

        2
  •  4
  •   G. Grothendieck    4 年前

    1) 是的。呼叫 使用 do.call 这个 a 参数可以使用 rep 。未使用包。

    a <- "tree"
    s <- "The %s is large but %s is small. %s"
    
    k <- length(gregexpr("%s", s)[[1]])
    do.call("sprintf", as.list(c(s, rep(a, k))))
    ## [1] "The tree is large but tree is small. tree"
    

    2) gsub公司 评论中已经提到了这一点,但 gsub 可以使用。同样,没有使用包。

    gsub("%s", a, s, fixed = TRUE)
    ## [1] "The tree is large but tree is small. tree"
    

    3) gsubfn gsubfn包支持准perl风格的字符串插值:

    library(gsubfn)
    
    a <- "tree"
    s2 <- "The $a is large but $a is small. $a"
    fn$c(s2)
    ## [1] "The tree is large but tree is small. tree"
    

    此外,反勾号还可以用来封装在中求值和替换的整个R表达式。

    这可以用于任何函数,而不仅仅是 c 导致代码非常紧凑。例如,假设我们要计算 s 之后 替代。然后可以这样做:

    fn$nchar(s2)
    ## [1] 38
    

    4) $n格式符号 在里面 sprintf 符号 %n$ 引用以下第n个参数 fmt :

    a <- "tree"
    s <- "The %1$s is large but %1$s is small. %1$s"
    sprintf(s, a)
    ## [1] "The tree is large but tree is small. tree"
    
        3
  •  3
  •   akrun    7 年前

    1) 我们可以使用 glue 。未使用包,除非

    glue::glue("The {s} is large but {s} is small. {s}", s = a)
    #The tree is large but tree is small. tree
    

    2. ) 语法 语法类似于python中的f-string方法

    a = "tree"
    print(f"The {a} is large but {a} is small. {a}")
    #The tree is large but tree is small. tree
    

    这与 format 方法,但更具可读性

    print("The {s} is large but {s} is small. {s}".format(s=a))
    #The tree is large but tree is small. tree