簡體   English   中英

在R中,您如何評估...在調用函數中?

[英]In R, how do you evaluate … in the calling function?

如果我想知道R函數中的...參數中存儲了什么,我可以簡單地將它轉換為列表,就像這樣

foo <- function(...)
{
  dots <- list(...)
  print(dots)
}

foo(x = 1, 2, "three")
#$x
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] "three"

我無法弄清楚的是如何在調用函數中評估... 在下一個例子中,我希望baz的內容將...參數返回到bar

bar <- function(...)
{
  baz()
}

baz <- function()
{ 
  # What should dots be assigned as?
  # I tried                                           
  # dots <- get("...", envir = parent.frame())
  # and variations of
  # dots <- eval(list(...), envir = parent.frame())
  print(dots)
}

bar(x = 1, 2, "three")

get("...", envir = parent.frame())返回<...> ,看起來很有希望,但我無法弄清楚如何從中提取任何有用的東西。

eval(list(...), envir = parent.frame())拋出錯誤,聲稱...使用不正確。

如何從bar檢索...

弄清楚了。 我需要evalsubstitute的組合。 baz應定義為

baz <- function()
{ 
  dots <- eval(substitute(list(...), env = parent.frame()))
  print(dots)
}

這應該工作:

bar <- function(...)
{
  baz(...=...)
}

baz <- function(...)
{ 
  print(list(...))
}

bar(x = 1, 2, "three")

只需在子功能中分配即可。

或者,您可以將省略號指定為父函數中的列表:

bar <- function(...)
{
  bar.x <- list(...)
  baz()
}

baz <- function()
{ 
  dots <- get("bar.x", envir = parent.frame())
  print(dots)
}

bar(x = 1, 2, "three")

這是同樣的想法,但我不建議,因為你覆蓋了省略號:

bar <- function(...)
{
  ... <- list(...)
  baz()
}

baz <- function()
{ 
  dots <- get("...", envir = parent.frame())
  print(dots)
}

bar(x = 1, 2, "three")

總之一句:不要。 試圖重新定義R的范圍規則只會導致痛苦和痛苦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM