【问题标题】:R: Can you make my ugly text concacting function prettyR:你能把我丑陋的文字拼接功能做得漂亮吗
【发布时间】:2014-05-26 17:25:39
【问题描述】:

我正在尝试编写一个函数,该函数使 R 解释参数而不评估它们并将它们推入一个新字符串。

这是我目前所拥有的。它非常难看,但最多可以使用 5 个:

pl <- pasteliteral <- 
function(v1='',v2='',v3='',v4='',v5='', sep="") {

 stopifnot(v1!="")

 # Sort up to 10 values
 if (deparse(substitute(v1)!=""))  {s<-deparse(substitute(v1))
 if (deparse(substitute(v2)!=""))  {s<-paste(s, deparse(substitute(v2)), sep=sep)
 if (deparse(substitute(v3)!=""))  {s<-paste(s, deparse(substitute(v3)), sep=sep)
 if (deparse(substitute(v4)!=""))  {s<-paste(s, deparse(substitute(v4)), sep=sep)
 if (deparse(substitute(v5)!=""))  {s<-paste(s, deparse(substitute(v5)), sep=sep)
 }}}}}
 s
}

pl(1,2,3,a,hello)
[1] "123ahello"

【问题讨论】:

  • 而且我知道这个函数没有可能的用途,除非一旦我拥有它,我会修改它以检查每个作为字符的参数是否存在,如果存在,我会将它们粘贴在一起.
  • 你可以用as.list(substitute(list(1,2,3,a,hello)))[-1]然后lapplydeparsedo.callpaste收集你的论点。

标签: r function arguments


【解决方案1】:

你可以试试sys.call:

pl <- pasteliteral <- function(..., sep="") {
  ## remove first element (the function name)
  ca <- sys.call()[-1]

  ## remove last element if it is sep     
  if (ca[[length(ca)]] == sep) {
    ca <- ca[-length(ca)]
  }
  paste0(ca, collapse=sep)
}

pl(1,2,3,a,hello)
# [1] "123ahello"

pl(1,2,3,a,hello, sep=":")
# [1] "1:2:3:a:hello"

【讨论】:

  • 这真的很有帮助。现在有没有机会告诉我如何将ca“语言”对象变成向量?
  • @fsmart:你的意思是例如as.character(ca)?
猜你喜欢
  • 2011-04-14
  • 1970-01-01
  • 2020-06-12
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多