Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use purrr for extracting elements from a list?

Tags:

r

purrr

I am trying to use purrr to access the level formatted_address from this list:

tt <- lapply(c('Austin, Texas', 'Houston, Texas'),  
function(x) ggmap::geocode(x, output='all', nameType = 'long', sensor = F))

The final output should be a vector of the elements from $ formatted_address : chr "Austin, TX, USA", namely c('Austin, TX, USA', 'Houston, TX, USA')

To start off, I was trying to grab the record for the first of the two elements of the list using standard indexing, and then converting it to purrr following this tutorial.

For instance, I thought

> tt[[1]]$results[[1]]$formatted_address
[1] "Austin, TX, USA"

Would be equivalent to the code below, but it isn't:

> map(tt[[1]]$results[[1]], 'formatted_address')
Error in map.poly(database, regions, exact, xlim, ylim, boundary, interior,  : 
  no recognized region names

Why aren't these two lines of code equivalent? And how could I use map or map_chr to create a vector of records from formatted_address?

like image 515
Dambo Avatar asked Jul 14 '17 12:07

Dambo


1 Answers

I think you have a naming conflict in your environment. As a result, the map function you are calling is another function from another package (probably the maps package, which matches the arguments listed in your error code, see here). Try to call the function with explicit context as below. Also, slightly change your syntax because otherwise your return will be empty.

purrr::map(tt, ~.x$results[[1]]$formatted_address)
like image 112
JanLauGe Avatar answered Nov 14 '22 22:11

JanLauGe