简体   繁体   中英

How do I use the ggmap library's get_map function inside of knitr?

All of my R code runs as expected in a standalone script. Once inside an R Markdown file the get_map() call breaks down.

map <- get_map(location = 'minneapolis', zoom = 9)

I get an error:

label: unnamed-chunk-2
Warning in sink() : no sink to remove
label: unnamed-chunk-2
Error in process_file(text) :
Quitting from lines 53-64: Error in close.connection(con) : invalid connection
Calls: knit -> process_file
Execution halted knitr terminated with status 1

Any ideas why knitr and get_map aren't playing nice?

It took me a while to figure out the problem. The root reason is ggmap was being "rude" to closeAllConnections() in four of its functions: mapdist() , geocode() , revgeocode() and route() ; knitr uses the evaluate package to evaluate R code, which opens text connections to record R output. Because ggmap has closed all connections, evaluate will not be able to close its connections again, which caused the error you saw. See https://github.com/hadley/evaluate/blob/master/R/watcher.r for details.

Normally one should be explicit about which connections to close using the close() function, and it is dangerous to use closeAllConnections() because this may close connections which are not supposed to be closed. I do not understand why the author has to use it, and I guess you need to report this issue to him. Finally we should be able to run this without errors:

library(evaluate); library(ggmap)
evaluate("map <- get_map(location = 'minneapolis', zoom = 9)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM