将参数传递给函数 [英] Pass arguments to function
问题描述
我在将参数传递给 R 中的函数时遇到了理解问题.
在以下示例中,我按名称从命名列表中检索值.当我直接执行时,它返回值.但是当我将相同的代码放入一个函数时,它返回 NULL.这里发生了什么?
提前致谢,米尔科
namedlist <- list(a=c("50", "80"), b=c("50"))命名列表$a# 返回: [1] "50" "80"myfunction <- function(arg){ namedlist$arg }我的功能(一)# 返回:NULL
您正在请求:
namedlist$arg
当然,namedlist
中没有名为 "arg"
的组件,因此返回值 NULL
.>
这种类型的子集列表将起作用:
myfunction <- function(arg) {命名列表[[arg]]}
并返回与namedlist$a相同的值,但您确实需要将组件名称作为字符串传递:
>命名列表$a[1] "50" "80">我的功能(一)myfunction(a) 中的错误:找不到对象a">我的功能(一个")[1] "50" "80"
I have an understanding problem with passing arguments to a function in R.
In the following example, I retrieve a value from a named list by name. When I do it directly, it returns the value. But when I put the same code into a function, it returns NULL. What happens here?
Thanks in advance, 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
You are requesting:
namedlist$arg
and of course there isn't a component with the name "arg"
in namedlist
, hence the return value NULL
.
this type of subsetting the list will work:
myfunction <- function(arg) {
namedlist[[arg]]
}
and returns the same as namedlist$a, but you do need to pass the component name as a string:
> namedlist$a
[1] "50" "80"
> myfunction(a)
Error in myfunction(a) : object 'a' not found
> myfunction("a")
[1] "50" "80"
这篇关于将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!