Function to get a value out of a list

How do you get an item out of a list using a function?

Example:

# the list
list <- list("a" = 1, "b" = 2, "c" = 3)

# this works
list$a

# but this doesn't
get_val <- function(list_name, item_name){
  list_name$item_name
}

# is NULL but should be 1
get_val(list, "a")

Actually, this seems to work:

get_val <- function(list_name, item_name){
  list_name[item_name]
}

get_val(list, "b")

the_list <- list("a" = 1, "b" = 2, "c" = 3)

get_val <- function(list_name, item_name) list_name[item_name][[1]]

get_val(the_list,"a")
#> [1] 1
2 Likes

Thanks for your help.

1 Like

There's also getElement function from base R.

the_list <- list("a" = 1, "b" = 2, "c" = 3)
getElement(the_list, "a")
#> [1] 1

But it's no surprise some people don't know about getElement. Base R has soooo many functions, and this one's only useful for passing as an argument to lapply or similar. Even then, I prefer to pass "[[" (which is a function). Less characters and anyone who's used R for a month knows how it works.

big_list <- list(c(a = 1, b = 2, c = 3), c(a = "A", b = "B", c = "C"))
lapply(big_list, getElement, "a")
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] "A"
lapply(big_list, "[[", "a")
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] "A"
2 Likes

Thanks for that. getElement() is good to know about.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.