【问题标题】:lapply in three dots construct in functionlapply in 三点构造函数
【发布时间】:2020-11-12 10:32:29
【问题描述】:

我正在尝试在用户定义函数的 3 点构造上实现 lapply。不知何故,它不起作用。

banner <- function(maintext,..., subtext = NULL) {
  
  if(length(list(...)) > 0) {
    
    dots <- lapply(X = list(...), FUN = function(x) tags$div(x))
    } else {
      dots <-  ''
    }
  
  HTML(paste0(
    
    "<div class='bannerbackground'> <h2>", maintext, "</h2>", 
              
  # If subtext specified
  ifelse(!is.null(subtext), paste0("<span>", subtext, "</span>", dots, "</div>"), paste0(dots, "</div>"))
              
  ))

}

banner('T1', 'T2', 'T3', subtext = 'T4')

我期待的输出

<div class='bannerbackground'> <h2>T1</h2><span>T4</span>
<div>T2</div>
<div>T3</div>
</div>

【问题讨论】:

    标签: r shiny lapply


    【解决方案1】:

    您使用点没有任何问题。您的问题是试图将 html 标签列表传递给 paste 函数。由于您最终要构建一个字符串,因此需要将它们转换为字符并粘贴为向量,而不是列表。因此,您需要sapply 而不是lapply

    banner <- function(maintext,..., subtext) {
    
      dots <- if(length(list(...))) sapply(list(...), function(x) as.character(tags$div(x)))
              else character()
      dots <- paste0("    ", dots, "\n", collapse = "")
    
      subtext <- if(!missing(subtext)) paste0("    <span>", subtext, "</span>\n") else ""
      
      HTML(paste0("<div class='bannerbackground'>\n  <h2>", 
                  maintext, 
                  "</h2>\n", 
                  subtext, 
                  dots, 
                  "</div>\n")
          )
    }
    

    提供格式精美的输出:

    banner('T1', 'T2', 'T3', subtext = 'T4')
    #> <div class='bannerbackground'>
    #>   <h2>T1</h2>
    #>     <span>T4</span>
    #>     <div>T2</div>
    #>     <div>T3</div>
    #> </div>
    

    顺便提一下,我已将is.null 更改为missing

    【讨论】:

    • 谢谢。不应该 subtext = NULL 因为它是一个可选参数,如果用户没有传递这个参数
    • @john 不,只要你用missing 测试来防范它的评估,就像我的例子一样。如果您进行测试,您将看到它按预期工作。
    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多