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

删除回忆录丶 提交于 2019-12-12 15:15:17

问题


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?


回答1:


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)")


来源:https://stackoverflow.com/questions/11162824/how-do-i-use-the-ggmap-librarys-get-map-function-inside-of-knitr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!