Reputation: 823
The purrr::map
function provides some shortcuts for selecting list elements: you can use a position by providing an integer, or a name by providing a string. An example here indicates that you can use a vector to deal with nested list elements. For example,
library(purrr)
library(repurrrsive) #includes example list data
gh_repos %>% map_chr(., c(1, 3))
navigates within each first position to retrieve and return the third list element.
Yet, when I tried to mix input using a position and name, it returns an error:
gh_repos %>% map_chr(., c(1, "full_name"))
#Error: Result 1 is not a length 1 atomic vector
The syntax can be represented several other ways to return the same results:
gh_repos %>% map_chr(c(1,3)) #Shown above
gh_repos %>% map(1) %>% map_chr("full_name")
gh_repos %>% map_chr(~pluck(.x, 1, "full_name"))
The last option was a discovery I made that approaches mixed inputs. I recognize that the mixed vectorized input is of a different class because it includes characters. Is this the reason it produces an error? What changes can I make to use mixed position and name inputs?
Upvotes: 1
Views: 105
Reputation: 206177
Yes, the problem is the different data classes. When you use c()
, everything gets coerced to the same atomic type . So c(1, "full_name")
is turned into c("1", "full_name")
which is a character vector. And the first list doesn't have a named element with the name "1"
. If you want to have mixed classes in R, you generally use lists. And it appears that map
supports lists. For example
gh_repos %>% map_chr(list(1, "full_name"))
# [1] "gaborcsardi/after" "jennybc/2013-11_sfu" "jtleek/advdatasci" "juliasilge/2016-14"
# [5] "leeper/ampolcourse" "masalmon/aqi_pdf"
Upvotes: 2