Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

r - Pass arguments to function

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...