nilsole
nilsole

Reputation: 1723

Iterate over list to get value by its name

This works. But are there more efficient/simpler ways to get output?

test_list <- list(list("name"="A","property"=1),
              list("name"="B","property"=2),
              list("name"="C","property"=3))

myFunction <- function(arg1=NULL, arg2=NULL){
  arg1[[arg2]]
}

# works
output <- sapply(test_list, myFunction, "property")

# returns NULL 
# output <- sapply(test_list, `$`, "property")

Upvotes: 1

Views: 105

Answers (1)

akrun
akrun

Reputation: 886968

We can specify the anonymous function call to do the extraction

sapply(test_list, function(x) x$property)
#[1] 1 2 3

Upvotes: 2

Related Questions