In short: How to extract one element from a list
@jmichaelrosenberg, for your purpose, you could use purrr
package from the tidyverse
and its new function pluck
to get one element for a list. Here is some reprex:
library(purrr)
# Get the first élement as in your example
list("a", "b", "c") %>%
pluck(1)
#> [1] "a"
A deeper element extraction : get the second element in the list that is the second element of the main list.
# With index
list(a = "a", b = list(b1 = "b1", b2 = "b2")) %>%
pluck(2, 2)
#> [1] "b2"
# or with name
list(a = "a", b = list(b1 = "b1", b2 = "b2")) %>%
pluck("b", "b2")
#> [1] "b2"
it is equivalent to list(a = "a", b = list(b1 = "b1", b2 = "b2"))[[2]][[2]]
Some explanation about the initial issue with your example code: about map
function
In your code there is a problem of syntax. map
applies a function to a each element of a list. The function could be define as an anonymous function (function(x) x[[1]]
) or with a special formula syntax (~ .x[[1]]
) - in your example your mixed both. As you use the second syntax, map
understood that it has to apply this function :
function() {
function(x) x[[1]]
}
It is why you have a result with a list of function. Correct use would be one of those:
library(purrr)
# syntax 1 : anonymous functions
list(A = list("a1","a2"), B = list("b1", "b2")) %>%
map(function(x) x[[1]])
#> $A
#> [1] "a1"
#>
#> $B
#> [1] "b1"
# syntax 2 : formula anonymous function
list(A = list("a1","a2"), B = list("b1", "b2")) %>%
map(~ .x[[1]])
#> $A
#> [1] "a1"
#>
#> $B
#> [1] "b1"
# syntax 3 : apply a function with argument
list(A = list("a1","a2"), B = list("b1", "b2")) %>%
map(`[[`, 1)
#> $A
#> [1] "a1"
#>
#> $B
#> [1] "b1"
# syntax 4 : purrr's map extraction feature
list(A = list("a1","a2"), B = list("b1", "b2")) %>%
map(1)
#> $A
#> [1] "a1"
#>
#> $B
#> [1] "b1"
As you see, each form extract the first element of each element of the input list for map
. As bonus, how to get a vector from this extraction : use map_chr
library(purrr)
list(A = list("a1","a2"), B = list("b1", "b2")) %>%
map_chr(1)
#> A B
#> "a1" "b1"