How to check if any arguments were passed via “…” (ellipsis) in R? Is missing(…) valid?

杀马特。学长 韩版系。学妹 提交于 2019-11-30 14:48:35

问题


I'd like to check whether an R function's "..." (ellipsis) parameter has been fed with some values/arguments.

Currently I'm using something like:

test1 <- function(...) {
   if (missing(...)) TRUE
   else FALSE
}

test1()
## [1] TRUE
test1(something)
## [2] FALSE

It works, but ?missing doesn't indicate if that way is proper/valid.

If the above is not correct, what is THE way to do so? Or maybe there are other, faster ways? PS. I need this kind of verification for this issue.


回答1:


Here's an alternative that will throw an error if you try to pass in a non-existent object.

test2 <- function(...) if(length(list(...))) FALSE else TRUE

test2()
#[1] TRUE
test2(something)
#Error in test2(something) : object 'something' not found
test2(1)
#[1] FALSE



回答2:


I think match.call is what you need:

test <- function(...) {match.call(expand.dots = FALSE)}

> test()
test()

> test(x=3,y=2,z=5)
test(... = list(x = 3, y = 2, z = 5))

It will give you every time the values passed in the ellipsis, or it will be blank if you won't pass any.

Hope that helps!




回答3:


If it helps anyone I ended up using the following function to get the ellipsis parameters for every function (returns an empty list or a list of arguments):

get.params <- function (...) {
  params <- list()

  if (length(list(...)) && !is.null(...)) 
    params <- unlist(...)

  return(params)
}

for:

f <- function(t, ...) {
 params <- get.params(...)
 print(paste(params))
}


来源:https://stackoverflow.com/questions/26684509/how-to-check-if-any-arguments-were-passed-via-ellipsis-in-r-is-missing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!