get_map 在 Markdown 文档中

get_map in Markdown document

以下代码

map<-get_map(location=params$chosenState, zoom=6,maptype='hybrid',source="google")
data<-sightings[sightings$State==params$chosenState, ]
ggmap(map, base_layer=ggplot(aes(x=lng,y=lat),data=data)) +geom_point(color="red",alpha=0.3)

在控制台上工作得很好,前提是我已经设置了一个名为 params 的数据框并将我的数据读入一个名为 sightings 的数据框。当 params$chosenState 为 "OH".

时,它会生成此图

然而,当我将所有内容移动到 Markdown 文档中时

---
title: "UFOs"
output: html_document
params:
  chosenState: "OH"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(ggmap)
library(ggplot2)
sightings<- read.csv("UFOs_coord.csv",header=TRUE)
UFOPlot<-function(){
  map<-get_map(location=params$chosenState, zoom = 6,maptype='hybrid',source="google")
  data<-sightings[sightings$State==params$chosenState, ]
  ggmap(map, base_layer=ggplot(aes(x=lng,y=lat),data=data))
}
```

## UFO Sightings

Below is the locations of UFO sightings in  ``r params$chosenState``
```{r}
UFOPlot()
```

去编织它,我收到这个错误信息

Error in if (is.waive(data) || empty(data)) return(cbind(data, PANEL = integer(0))) : missing value where TRUE/FALSE needed Calls: ... lapply -> FUN -> -> f -> -> f

我想知道是否缺少有关在 Markdown 中使用 ggmap 的一些基本知识?这是我第一次尝试这样做。

这是数据帧数据的开始

     Date...Time Country          City State    Shape      lat       lng
9   12/19/16 18:30     USA Huber Heights    OH Cylinder 39.85902 -84.11136
21  12/18/16 19:00     USA     Lancaster    OH    Light 39.71368 -82.59933
321 11/18/16 23:30     USA      Columbus    OH Cylinder 39.96226 -83.00071
326 11/18/16 19:15     USA   Stone Creek    OH Triangle 40.39729 -81.56206
327 11/18/16 18:30     USA    Carrollton    OH   Circle 40.57284 -81.08565
336 11/17/16 21:30     USA        Athens    OH    Light 39.32924 -82.10126

更新:

也许我的逻辑下标有问题? dplyr 和 Dhiraj 建议的 ggmap 调用似乎可以解决问题。这份文件编织得很好

---
title: "UFOs"
output: html_document
params:
  chosenState: "OH"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message= FALSE, warning=FALSE)
library(ggmap)
library(ggplot2)
library(dplyr)
sightings<- read.csv("UFOs_coord.csv",header=TRUE)
UFOPlot<-function(){
  map<-get_map(location=params$chosenState, zoom = 6,maptype='hybrid',source="google")
  data <- sightings %>% select(-Summary, -Shape) %>% filter(State==params$chosenState)
  ggmap(map) + geom_point(data=data, aes(x=lng,y=lat), color="red", alpha=0.3)

}
```
## UFO Sightings

Below is the locations of UFO sightings in  ``r params$chosenState``
```{r}
UFOPlot()
```

我在 rmarkdown 文件的代码块中尝试了以下内容,它似乎工作正常:

library(ggmap)
lat <- 39.86+rnorm(10,0.5)
lng <- -82.59 + rnorm(10, 0.5)
sightings <- data.frame(cbind(lng,lat))

map<-get_map(location='Ohio', zoom = 6,maptype='hybrid',source="google")
ggmap(map) + geom_point(data=sightings, aes(x=lng,y=lat))