传递参数给函数

4

我在R语言中传递函数参数方面存在一些理解问题。

在下面的例子中,我通过名称从命名列表中检索值。当我直接这样做时,它会返回该值。但是当我将相同的代码放入一个函数中时,它会返回NULL。这里发生了什么?

谢谢,Mirko

namedlist <- list(a=c("50", "80"), b=c("50")) 

namedlist$a
# returns: [1] "50" "80"

myfunction <- function(arg){ namedlist$arg }
myfunction(a)
# returns: NULL
1个回答

7
您正在请求:
namedlist $ arg
当然,在 namedlist 中没有名为 "arg" 的组件,因此返回值为 NULL。
这种类型的列表子集将起作用:
myfunction <- function(arg) {
    namedlist[[arg]]
}

返回与namedlist$a相同的内容,但您需要将组件名称作为字符串传递:

> namedlist$a
[1] "50" "80"
> myfunction(a)
Error in myfunction(a) : object 'a' not found
> myfunction("a")
[1] "50" "80"

2
@Mirko 此外,您在这里依赖于作用域查找全局工作区中的内容。更好的做法是编写 myfunction 使其自包含,并将所需的所有对象作为参数传递。myfunction <- function(list, arg) 并将以下内容作为函数体 list[[arg]],并通过 myfunction(namedlist, "a") 调用它。 - Gavin Simpson
我删掉了我的,你的更完整 :) - Prasad Chalasani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接