R函数技术疑问:return语句内的表达式为何无法求值?
Hey there! Let's break down what's going wrong with your function and how to fix it quickly.
First, let's look at your original code:
f=function(x){return(list(y=x, z = y))}; f(1)
The Root Cause
When you run this, you'll get an error saying Error in list(y = x, z = y) : object 'y' not found. Here's why:
In R, when you define the list inside return(), the y you're trying to use for z = y doesn't exist in the function's working environment yet. The y=x part is just defining a named element of the list, not creating a variable y that you can reference elsewhere in the same list definition. R looks for a variable named y in the current scope (the function's environment) and can't find it—hence the error.
Easy Fixes
You have a couple of straightforward ways to fix this:
Create the
yvariable first
Defineyas a separate variable in the function before building the list. This makesyavailable to use when settingz:f=function(x){ y <- x return(list(y=y, z=y)) } f(1)Reuse the original
xdirectly
Ifyis just a direct copy ofx, you can skip creating a separate variable and just usexfor both list elements:f=function(x){return(list(y=x, z=x))} f(1)
Either of these will return the expected output:
$y [1] 1 $z [1] 1
内容的提问来源于stack exchange,提问作者kevin

