【问题标题】:R paste function repeats first argument for each wordR粘贴函数为每个单词重复第一个参数
【发布时间】:2019-01-30 03:13:25
【问题描述】:

下面是用于编写消息的代码 sn-p。但我不明白为什么输出打印方式如下。还给出了预期输出。我首先认为 txt 是列表类型。但它是一个字符变量

writetext<-function(...){
   arguments <- list(...)
 if (length(arguments)>0){
   txt<- paste(arguments)
   if (length(txt)==0) return()
   strtime <- format(Sys.time(),"%I:%M:%S%p")
   txt <- paste(strtime,txt)
   message(txt)

} }

writetext("abc","efg")  
01:05:13PM abc01:05:13PM efg

Expected :
01:05:13PM abcefg

【问题讨论】:

  • 来自paste 的帮助页面:If the arguments are vectors, they are concatenated term-by-term to give a character vector result。这就是为什么你会得到看起来像多个输出的原因;这是paste 的默认行为(没有在 Jozef 给出的答案中指定collapse),

标签: r


【解决方案1】:

你可以使用paste0(txt, collapse = "")

writetext <- function(...) {
  arguments <- list(...)
  if (length(arguments) > 0) {
    txt <- paste(arguments)
    if (length(txt) == 0) return()
    strtime <- format(Sys.time(), "%I:%M:%S%p")
    txt <- paste(strtime, paste0(txt, collapse = ""))
    message(txt)
  }
}

writetext("abc", "efg") 
# 07:13:45PM abcefg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多