4

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

1 Answer 1

7

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"
Sign up to request clarification or add additional context in comments.

2 Comments

@Mirko in addition, you are relying here on scoping finding something in the global workspace. It would be better practice to write myfunction such that it is self-contained and you pass in all objects required as arguments. myfunction <- function(list, arg) and have the following as the function body list[[arg]], and call it via myfunction(namedlist, "a")
I deleted mine, yours is more complete :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.