You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中如何让函数调用时使用内部定义的变量作为参数?

Understanding the Scoping Issue in Your R Function

First, let's break down what's happening in your original code:

my_function <- function(...){ 
  x <- 10 
  sum(...) 
} 
my_function(x)

When you call my_function(x), R evaluates the argument x in the calling environment (the place where you run this line, like the global environment). If x isn't defined there, you'll get an error. The local x <- 10 inside the function doesn't affect this call because you're passing x as an argument via ....

If your goal is to force the function to look for x in its enclosing environment (the environment where my_function was created, not where you call it)—even if that environment has no x (leading to the error you want)—here are two practical approaches:

1. Evaluate Arguments in the Enclosing Environment

To make arguments passed via ... evaluate in the enclosing environment of my_function instead of the calling environment, use match.call() and eval() to override the default behavior:

my_function <- function(...){ 
  x <- 10 
  # Capture the arguments passed to the function
  call_args <- match.call(expand.dots = TRUE)[-1]
  # Evaluate each argument in the enclosing environment of the function
  evaluated_args <- lapply(call_args, eval, envir = parent.env(environment()))
  # Sum the evaluated arguments
  do.call(sum, evaluated_args)
}

Now, when you run my_function(x), R will search for x in the environment where my_function was defined (e.g., the global environment). If x isn't present there, you'll get the "object 'x' not found" error you're targeting.

2. Bypass Local Variables to Use the Enclosing Environment

If you want to directly reference x from the enclosing environment inside the function (instead of passing it as an argument)—even though the function has its own local x—use get() with the envir argument to explicitly specify where to look:

my_function <- function(){ 
  x <- 10 
  # Look for x in the enclosing environment, ignoring the local variable
  sum(get("x", envir = parent.env(environment())))
}

Calling this function without arguments (my_function()) will attempt to find x in the enclosing environment. If it doesn't exist, you'll get the error you expect.

Quick Note on R Scoping

R uses lexical scoping: when a function references a variable, it checks its own local environment first, then the enclosing environment (where the function was created), then that environment's parent, and so on up to the global environment. By default, function arguments are evaluated in the calling environment, not the enclosing one.

内容的提问来源于stack exchange,提问作者Ross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:54:42