传递参数的功能 [英] Pass arguments to function

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

问题描述

我有传递参数的理解问题在R的功能

在下面的例子中,我检索名字命名列表的值。当我这样做,直接,它返回值。但是,当我把同样的code到一个函数,它返回NULL。在这里会发生什么?

在此先感谢,
米尔科

  namedlist<  - 表(A = C(50,80后),B = C(50))namedlist $一个
#回报:[1]5080MyFunction的< - 功能(ARG){$ namedlist ARG}
myfunction的(一)
#返回:NULL


解决方案

您正在请求:

namedlist $ ARG

当然没有名为ARG namedlist ,因此回报组件值 NULL

这种类型的子集列表将工作:

  myfunction的<  - 功能(ARG){
    namedlist [[参数]
}

和返回同样namedlist $一个,但你需要传递组件名称为一个字符串:

 > namedlist $一个
[1]5080
> myfunction的(一)
在MyFunction的(一)错误:对象'一'未找到
> myfunction的(一)
[1]5080

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆