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

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

问题描述

我很困惑 ... 是如何工作的.

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天全站免登陆