将可选参数传递给函数,三个点 [英] Pass optional arguments to function, three dots

查看:109
本文介绍了将可选参数传递给函数,三个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑...的工作方式.

I'm confused how ... works.

tt = function(...) {
  return(x)
}

为什么tt(x = 2)不返回2?

相反,它失败并显示以下错误:

Instead it fails with the error:

tt(x = 2)中的错误:找不到对象'x'

Error in tt(x = 2) : object 'x' not found

即使我将x作为参数传递?

Even though I'm passing x as argument ?

推荐答案

因为您在...中传递的所有内容都保留在...中.您传递的未由参数明确捕获的变量不会扩展到本地环境中. ...应该用于您当前函数根本不需要与之交互的值,但是某些后来的函数确实需要使用它们,因为它们可以很容易地在...内部传递.这是针对类似

Because everything you pass in the ... stays in the .... Variables you pass that aren't explicitly captured by a parameter are not expanded into the local environment. The ... should be used for values your current function doesn't need to interact with at all, but some later function does need to use do they can be easily passed along inside the .... It's meant for a scenario like

ss <- function(x) {
   x
}

tt <- function(...) {
  return(ss(...))
}

tt(x=2)

如果您的函数需要定义变量x,则应将其作为参数

If your function needs the variable x to be defined, it should be a parameter

tt <- function(x, ...) {
  return(x)
}

如果您真的想将点扩展到当前环境中(强烈建议您不要这样做),则可以执行类似

If you really want to expand the dots into the current environment (and I strongly suggest that you do not), you can do something like

tt <- function(...) {
  list2env(list(...), environment())
  return(x)
}

这篇关于将可选参数传递给函数,三个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆