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
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"
Thanks for that. getElement() is good to know about.