【问题标题】:Three-dots construct in R [duplicate]R中的三点构造[重复]
【发布时间】:2018-09-23 11:27:33
【问题描述】:

这可能以前被问过,但我还没有找到任何相关的问题/答案(还没有?)。

来自Python*args**kwargs),我试图将... 构造理解为R 中的函数参数。

假设,我们有

test <- function(x, ...) {
  print(...)
}

test(x=c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12))

为什么它只产生

[1] 4 5 6

以及如何迭代多个参数(如果有的话)?

【问题讨论】:

  • 学习help("print")。它的第一个参数是要打印的值。您基本上是在这样做 print.default(x = c(4.12345678,5,6), digits= c(7,8,9), quote = c(10,11,12))print.default 默默地使用向量的第一个值(例如,digits= 7)作为其他参数。
  • @Roland:谢谢你的解释。

标签: r


【解决方案1】:
test <- function(x, ...) {
  # these are equivalent and print prints only its first argument, see ?print
  print(c(4,5,6), c(7,8,9), c(10,11,12))
  print(...)

  # here's how you can get the dots
  a <- eval(substitute(alist(...))) # unevaluated dots
  # or
  a <- list(...) # evaluated dots (works fine as well  in this case)
  a
}

test(x=c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12))
# [1] 4 5 6
# [1] 4 5 6
# [[1]]
# c(4, 5, 6)
# 
# [[2]]
# c(7, 8, 9)
# 
# [[3]]
# c(10, 11, 12)

【讨论】:

  • 为什么我应该使用 eval(substitute(list(...))) 而不仅仅是 list(...) ?比后者有什么优势吗?
  • 实际上对于这种情况它并没有改变任何东西,但是我建议不要对点进行评估,尝试将它放在函数的主体中:print(str(eval(substitute(alist(...))))); print(str(list(...)))
  • 所以如果你尝试test(x, a,b,c)而不定义参数你会看到list(...)会失败而eval(substitute(alist(...))不会。
猜你喜欢
  • 2021-01-28
  • 2020-11-12
  • 2015-06-20
  • 2012-01-17
  • 2017-06-19
  • 2020-02-16
  • 2016-09-26
  • 2021-09-25
  • 1970-01-01
相关资源
最近更新 更多