Accessing the internet with knitr - google-maps

When I run some code to draw a map using ggmap, in Rstudio it runs fine. When I run it using knitr it fails with the following error message:-
Error in download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") :
cannot open URL 'http://maps.googleapis.com/maps/api/staticmap?center=-40.851253,172.799669&zoom=19&size=%20640x640&scale=%202&maptype=hybrid&sensor=false'
Calls: ... eval -> eval -> get_map -> get_googlemap -> download.file
In addition: Warning message:
In download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") :
unable to connect to 'maps.googleapis.com' on port 80.
Execution halted
I am sure this is due to the way our network is set up, probably around permissions, but is anyone able to give me any clues as to how knitr would try to access the internet to download a map so I may be able to find a way though our firewall.
Code added but it works fine except through our network.
---
title: "Drawing a map"
author: "Alasdair Noble"
output: word_document
---
To draw a map
```{r echo=TRUE, warning=FALSE , results='markup', comment="",message=FALSE }
library(ggplot2)
library(grid)
library(GGally)
library(plyr)
library(RColorBrewer)
library(ggmap)
library(ggthemes)
```
```{r echo=TRUE, warning=FALSE , results='markup', comment="", message=FALSE }
Btrcup <- get_map(location=c(lon=171.799669, lat=-42.851253),zoom=19, maptype="hybrid")
Btrcupmap <- ggmap(Btrcup)
Btrcupmap
```

Related

Generating a downloadable html quarto document from a shiny app on shinyapps.io

The following app (reproducible example) works perfectly when deployed locally, but not when hosted on shinyapps.io. My understanding is that the quarto::quarto_render() call should have permission to write a file on shinyapps.io (it wouldn't be persistent from instance to instance, but that's fine). Does shinyapps.io not support quarto rendering? If not, does it support RMarkdown and would this code be expected to work with the appropriate conversions?
app.R:
library(shiny)
library(quarto)
ui <- fluidPage(
titlePanel("Reproducable Example"),
sidebarLayout(
sidebarPanel(
textInput(inputId = "user.name", label = "User name:"),
br(),
downloadButton(outputId = "report", label = "Generate Report:")
),
mainPanel(
)
)
)
server <- function(input, output) {
output$report <- downloadHandler(
filename = "Reprod_ex.html",
content = function(file) {
quarto::quarto_render("myquarto.qmd",
execute_params = list(username = input$user.name))
file.copy("qmd_output.html", file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
myquarto.qmd:
---
format:
html:
toc: false
anchor-sections: false
fig-cap-location: bottom
tbl-cap-location: top
number-sections: false
smooth-scroll: true
self-contained: true
css: my-style.css
output-file: "qmd_output.html"
params:
username: NA
---
# Heading
My name is `r params$username`.
quarto package itself does not include quarto binaries and currently quarto is not available at shinyapps.io, there's also an open issue on this - https://github.com/rstudio/shinyapps-package-dependencies/issues/332
Though RMarkdown works fine there, at least with that sample qmd and with few changes in content function:
content = function(file) {
rmarkdown::render("myquarto.qmd", params = list(username = input$user.name))
file.copy("myquarto.html", file)
}
To get some insights about quarto you can call quarto::quarto_path() and quarto::quarto_version() :
library(shiny)
library(quarto)
ui <- fillPage(
verbatimTextOutput(outputId = "quarto")
)
server <- function(input, output) {
output$quarto <- renderText({
paste0("quarto::quarto_path(): ",quarto::quarto_path(),"\n",
"quarto::quarto_version(): ", quarto::quarto_version()
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
On a local Windows / RStudio installation this renders as:
quarto::quarto_path(): C:\PROGRA~1\RStudio\RESOUR~1\app\bin\quarto\bin\quarto.exe
quarto::quarto_version(): 1.2.269
When deployed to shinyapps.io :
An error has occurred. Check your logs or contact the app author for clarification.
shinyapps.io logs:
2023-01-27T15:34:47.308135+00:00 shinyapps[8147981]: Listening on http://127.0.0.1:39585
2023-01-27T15:34:49.804410+00:00 shinyapps[8147981]: Warning: Error in find_quarto: Unable to find quarto command line tools.
2023-01-27T15:34:49.816843+00:00 shinyapps[8147981]: 115: stop
2023-01-27T15:34:49.816876+00:00 shinyapps[8147981]: 114: find_quarto
2023-01-27T15:34:49.816881+00:00 shinyapps[8147981]: 113: quarto::quarto_version
2023-01-27T15:34:49.816889+00:00 shinyapps[8147981]: 111: renderText [/srv/connect/apps/quarto_test/app.R#10]

R: Converting "rmarkdown" to "html" files

I am using the R programming language. I am trying to recreate the interactive "dashboard" from this website : https://beta.rstudioconnect.com/jjallaire/htmlwidgets-rbokeh-iris/htmlwidgets-rbokeh-iris.html (code is provided on this website).
First, I ran this code to access the "flexdashboard template maker" :
library(flexdashboard)
rmarkdown::draft("dashboard.Rmd", template = "flex_dashboard", package = "flexdashboard")
Then, I deleted all the text in the window that popped up. I copied the R code from the website (https://beta.rstudioconnect.com/jjallaire/htmlwidgets-rbokeh-iris/htmlwidgets-rbokeh-iris.html) into this window and clicked "save":
---
title: "rbokeh iris dataset"
author: "Ryan Hafen"
output:
flexdashboard::flex_dashboard:
orientation: columns
social: menu
source_code: embed
---
```{r setup, include=FALSE}
library(rbokeh)
library(flexdashboard)
```
Column {data-width=600}
-----------------------------------------------------------------------
### Species
```{r}
figure(width = NULL, height = NULL) %>%
ly_points(Sepal.Length, Sepal.Width, data = iris, color = Species)
# figure() %>%
# ly_points(Sepal.Length, Sepal.Width, data = iris,
# color = Species, glyph = Species)
```
Column {data-width=400}
-----------------------------------------------------------------------
### Species (Quantile)
```{r}
figure(width = NULL, height = NULL, legend_location = "top_left") %>%
ly_quantile(Sepal.Length, group = Species, data = iris)
```
### Petal Width
```{r}
figure(width = NULL, height = NULL) %>%
ly_points(Sepal.Length, Sepal.Width, data = iris,
color = Petal.Width)
```
This file ("dashboard.Rmd") is saved in "my documents" (which has been also set to the default working directory):
Now, I want to "view" the dashboard and "save" the dashboard as an ".html" file. I found this other stackoverflow post that shows how to solve this problem: How to convert R Markdown to HTML? I.e., What does "Knit HTML" do in Rstudio 0.96?
I tried to follow the steps in one of the answers provided on this stackoverflow post:
require(knitr) # required for knitting from rmd to md
require(markdown) # required for md to html
markdownToHTML('dashboard.Rmd', 'test.html')
But this produced the following output (incorrect):
Instead of the desired output:
Can someone please show me what I am doing wrong and how can I fix this (i.e. get the desired output) ?
Thanks
After you save the file in dashboard.Rmd, click on Knit -> Knit to flex_dasboard
This opens the dashboard template in RStudio itself. This also automatically creates a HTML file with the same name (dashboard.html) in your working directory.

Errors when knitting RMarkdown to HTML (no graphs showing up in the HTML)

Question about knitting RMarkdown.
I am having issues when knitting a Rmarkdown file to HTML/pdf. When I run my chunks of code in the Rmarkdown file everything runs smoothly (and I get my graphs made with ggplot) but when knitting I get an output with no graphs and errors (error in eval, error in ggplot, error in print).
Does anyone have experience with this?
The errors:
Error in eval(lhs, parent): object ‘iso3166’ not found
Error in ggplot(inci_100k, aes(long, lat, map.id=mapname,fill=inci)): object ‘inci_100k’ not found
Error in print(INCIPLOT): object ‘INCIPLOT’ not found
The code:
---
title: "R Markdown MAP"
author: "Alexandra V"
date: "1/4/2020"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r,echo = FALSE, warning = FALSE, message=FALSE, error=TRUE}
knitr::opts_chunk$set(cache=TRUE)
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(error = TRUE)
```
Loading the packages we will need for the following analysis.
```{r echo=FALSE, warning=FALSE}
library(tidyverse)
library(lubridate)
library(ggmap)
library(countrycode)
library(grid)
library(gridExtra)
```
To only keep the data needed to make a worldmap of TB incidences, only the relevant data will be taken from the TB_burden_countries_2020-01-04.csv file. Column 1: country names, column 3: iso3 (country codes), column 6: years, column 8: e_inc_100k (estimated incidence all TB forms per 100.000). To make the file easier to work with the names of the columns will be changed to: country, code, year and inci respectively.
```{r, message=FALSE}
TB.burden <- read.csv("TB_burden_countries_2020-01-04.csv")
TBworldINC.map <- as.data.frame(TB.burden[,c(1,3,6,8)], drop=false)
write.csv(TBworldINC.map, 'TBworldINC.map.csv', row.names = FALSE)
tb.INC <- read_csv("TBworldINC.map.csv") %>%
setNames(c("country", "code", "year", "inci"))
```
```{r}
world <- map_data("world")
tb_some_years <- tb.INC %>%
filter(year %in% c(2005, 2010, 2015, 2018))
inci_100k <- tb_some_years %>%
inner_join(iso3166 %>% select(a3, mapname), by = c(code = "a3")) %>%
left_join(world, by = c(country = "region"))
INCIPLOT <- ggplot(inci_100k, aes(long, lat, map_id = mapname,
fill = inci)) +
geom_map(map = world) +
scale_fill_gradient(low = "blue", high = "yellow") +
theme_void() +
coord_map(xlim = c(-180, 180)) +
labs(fill = "Incidence per year") +
facet_wrap(~ year, ncol = 2)
print(INCIPLOT)
```
picture of the output I get in Rstudio
I have had similar issues when making maps in R. One work around is to create your graphs and to save it locally and including the images. The syntax for adding images in R Markdown is ![alt text](path to image)

Empty Controls and No Plot with rCharts + Rmarkdown + RStudio

I am unable to get a desired HTML from running the code below. I attached the resulting "Output" file as a snapshot. The controls are empty and there is no plot. What am I doing wrong?
Thank you.
Rmarkdown code:
---
title: "Test"
output: html_document
---
```{r, echo=FALSE, results='asis', cache=FALSE}
#install.packages("devtools")
require(devtools)
install_github("ramnathv/rCharts")
install_github("yihui/knitr")
library(rCharts)
library(knitr)
n1 <- rPlot(mpg ~ wt, data = mtcars, color = "gear", type = "point")
n1$addControls("x", value = "wt", values = names(mtcars))
n1$addControls("y", value = "wt", values = names(mtcars))
n1$addControls("color", value = "gear", values = names(mtcars))
n1$show('iframesrc', cdn = TRUE)
```
My setup:
Windows 7 Pro, 64 bit.
RStudio version 0.99.892.
Note to install devtools when running the code attached.
I click on "Knit HTML" in RStudio to build.

How to load online JSON data to shiny app with jsonlite?

I am trying to make shiny app that takes data from this api: https://www.riigiteenused.ee/api/et/all. I need to use jsonlite::fromJSON, because it has good flatten function. When I use the following code (minimal example, in real life I do more stuff with data):
library(jsonlite)
data=fromJSON("https://www.riigiteenused.ee/api/et/all")
server <- function(input, output) {
output$tekst <- renderText({
nchar(data)
})
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(textOutput("tekst"))
))
shinyApp(ui = ui, server = server)
I get following error message:
Error in open.connection(con, "rb") :
Peer certificate cannot be authenticated with given CA certificates
I tried the following (go around ssl verify peer):
library(RCurl)
raw <- getURL("https://www.riigiteenused.ee/api/et/all",
.opts = list(ssl.verifypeer = FALSE), crlf = TRUE)
data=fromJSON(raw)
It reads in raw data, but messes up JSON (validate(raw) shows lexical error: invalid character \n inside string, which is causing following error):
Error: lexical error: invalid character inside string.
ressile: laevaregister#vta.ee. Avaldusele soovitatavalt lis
(right here) ------^
Also one idea I tried was:
data=fromJSON(readLines("https://www.riigiteenused.ee/api/et/all"))
It works fine in my computer, but when I upload it to shinyapps.io app doesn't work and from logs I see error:
Error in file(con, "r") : https:// URLs are not supported
Could somebody give me a clue, if there is a way to load JSON data from https toshiny app using jsonlite fromJSON function?
My session info is following:
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)
locale:
[1] LC_COLLATE=Estonian_Estonia.1257 LC_CTYPE=Estonian_Estonia.1257
[3] LC_MONETARY=Estonian_Estonia.1257 LC_NUMERIC=C
[5] LC_TIME=Estonian_Estonia.1257
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] jsonlite_0.9.19 httr_1.0.0 RCurl_1.95-4.7 bitops_1.0-6 shiny_0.12.2
loaded via a namespace (and not attached):
[1] Rcpp_0.12.2 digest_0.6.8 mime_0.4 R6_2.1.1
[5] xtable_1.7-4 magrittr_1.5 stringi_1.0-1 curl_0.9.4
[9] tools_3.2.2 stringr_1.0.0 httpuv_1.3.3 rsconnect_0.4.1.4
[13] htmltools_0.2.6
don't skip ssl, try
fromJSON(content(GET("https://www.riigiteenused.ee/api/et/all"), "text"))
I tried this solution that worked fine in my computer and in shiny server:
library(rjson)
library(jsonlite)
fromJSON(url, flatten=T)