R markdown won't knit to pdf - r

I am trying to knit my Rmarkdown document to pdf however it keeps coming up with this message:
Error: Failed to compile R_Markdown.tex. See https://yihui.name/tinytex
/r/#debugging for debugging tips.In addition: Warning message:In
readLines(logfile) : incomplete final line found on
'R_Markdown.log'Execution halted
It is fine when knitting to html and word but not pdf, I have MiKTex installed with the latest updates so what is the problem? I have attached my code below:
---
title: 'Maths Skills 2: Recent advances in statistics project'
author: "Jamie Tse"
date: "28 March 2019"
output: pdf_document
---
#Part A: UK fishing Vessels
The goal of this part of the project is to provide a graphical representation of the geographical distribution of
UK fishing vessels under 10 metres in length.
## Creating a map of the UK using ggmap
I begin by loading the `tidyverse` and `ggmap` packages:
```{r,eval=FALSE}
library(ggmap)
library(tidyverse)
I then found an appropriate bounding box to cover the UK was
bbox <- c(-9.05, 48.77, 2.19, 61)
Then, using this bounding box I created the map UKmap by using the ggmap() function:
UKmap <- ggmap(get_map(location = bbox, source = "stamen", maptype = "toner"))
Reading in the shipping vessels Data
After creating my map on which to plot the data, I read in the shipping vessels data and saved it to vessels using the read.csv() function
vessels <- read.csv("Jan_2019_Under_10m_vessel_list.csv")

Related

All tmap::qtm() plot titles are appearing in a single plot rather than their own

I am currently writing a .Rmd (R markdown document) on downloading and visualising the Local Authority Districts (LADs) and transport regions of the UK within Rstudio.
> R.version
_
platform x86_64-pc-linux-gnu
arch x86_64
os linux-gnu
system x86_64, linux-gnu
status
major 4
minor 2.0
year 2022
month 04
day 22
svn rev 82229
language R
version.string R version 4.2.0 (2022-04-22)
I am doing this in a .Rmd so that this document can be hosted on github as a vignette.
I am having an issue whereby I have four separate plots which should all have unique titles set with qtm(title = 'desired_title') as per the documentation, however all titles are being assigned to my first plot and none of the plots after, even though the other plots are building correctly (legend, polygon colours etc.)
I have been knitting the document locally to view my changes rather than uploading every edit to GH to visualise my edits (knitr version: 1.39)
Here are the steps to reproduce my issue
library(sf)
library(tmap)
library(dplyr)
# Download data from the openinfra repo
url_regions_lad = "https://github.com/udsleeds/openinfra/raw/main/data-small/lads_joined_2021.geojson"
url_transport_regions = "https://github.com/udsleeds/openinfra/raw/main/data-small/regions_new.geojson"
# Load data into a Simple Features frame
regions_lad = read_sf(url_regions_lad)
transport_regions = read_sf(url_transport_regions)
# Set tmap mode to interactive
tmap::tmap_mode('view') # After this, all tmap::qtm() plots will be interactive
# Here we create the interactive plots
sf::sf_use_s2(use_s2 = FALSE)
regions_lad %>% tmap::qtm(title = 'LADs of UK & NI')
# Here we create an interactive plot of all LADs, coloured by the region they reside in
tmap_options(max.categories = 78) # Increase max categories so every (78) transport region has its own colour
regions_lad %>% tmap::qtm(fill = 'Region_name', title = 'LADs of UK & NI coloured by region')
# Here we plot the transport regions of England
transport_regions %>% tmap::qtm(title = 'Transport regions of England')
# Here we create the coloured interactive plot of England's transport regions
transport_regions %>% tmap::qtm(title = 'Coloured transport regions of England', fill = 'Region_name')
Note that sf::sf_use_s2(use_s2 = FALSE) is a fix for errors (1 2) due to an upgrade to the sf package
What I expect:
I expect to see each of the four plots with their own respective titles added
What I get:
Instead I have all four of my plot titles (the most recently created being the top title) added to the first plot and none after.
Single plot with all 4 titles on
The figures themselves are building correctly (This one has coloured all LADs) with the exception of titles, as can be seen in this example.
See the vignette hosted on GH here

R Markdown flexdashboard output not producing ggplotly graphs

Please help regarding one issue that I have with the output I am getting with R Markdown-flexdashboard. I suppose I am doing something wrong.
I am using the following code in Rmarkdown:
title: "Economy and Population in Croatia 2000-2017"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
library(flexdashboard)
library(tidyverse)
library(plotly)
library(ggrepel)
library(reshape2)
library(viridis)
library(DT)
load("my_work_space.RData")
Page 1 - National level
Column {data-width=600, .tabset}
Croatia 2000-2017: Population and Economy
g1
Croatia by County: Population 2018
ggplotly(g4)
Croatia by County: Economy 2017
ggplotly(g5)
Column {data-width=400}
Croatia: Economy and Demography by County
datatable(data = Datatable_Demo_Econs,
rownames=FALSE,
options=list(pageLength=3))
GDP of Regions 2000-2017
ggplotly(g2, tooltip = c("Region", "Year"))
Here are the pics of the code in the Rmarkdown code-pic1, code-pic2
However, I only manage to create the first plotly plot (g1) in the flexdashboard. Other graphs are produced via ggplotly (maybe that is the problem?). It looks like some kind of bug for ggplotly graphs in flexdash Rmarkdown script, or I am doing something wrong.
I am attaching the picture to see the almost empty flexdashboard.
Empty flexdashboard
It is confusing for me that exactly the same code produced the correct and full flexdashboard if I am using RStudio Cloud. I am attaching two pictures of correct and full dashboard produced in RStudio Cloud:
1. pic: correct flexdash
2. pic: correct flexdash
Thanks

Difference generating image between .Rmd and .R

The code below is a full .Rmd file that successfully generates a .pdf file with a hovmoller plot of surface temperature. (I apologize for pasting the whole file, but it is short and I'm not sure what might be causing the problem - though I believe it is in the last section of the code.) The data file is here: https://crudata.uea.ac.uk/cru/data/temperature/HadCRUT.4.6.0.0.median.nc
When I run the .Rmd file, it seems to work flawlessly. It generates a .pdf file that is 230kb that contains a (rather informative) hovmoller plot. If, however, I put the code into a .R file (or run it line by line from the .Rmd file), it still generates a .pdf file, but it is empty and generates an error message if I try to open it.
Can anybody tell me why this happens?
---
title: "Hovmoller plot - HadCRUT4 through November 2018"
author: "jbtg"
date: "January 1, 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r warning=FALSE,message=FALSE}
library(maptools)
library(ncdf4)
library(raster)
library(rasterVis)
library(RColorBrewer)
library(zoo)
library(sf)
library(rgdal)
```
```{r}
#HADCRUT4 combined air temp/SST anomaly as of November 1, 2018
#read a 3D netCDF dataset
hadcrut4_path <- "C:/Users/jtene/Dropbox/!!!netcdf/Rmarkdown/"
hadcrut4_name <- "HadCRUT.4.6.0.0.median.nov18.nc"
hadcrut4_file <- paste0(hadcrut4_path,hadcrut4_name)
hadcrut4 <- brick(hadcrut4_file) #opens anomaly netCDF file (calls nc_open)
hadcrut4 #gives a summary of the file contents
print(c(filename(hadcrut4), hasValues(hadcrut4), inMemory(hadcrut4)))
```
Set up and produce the Hovmöller plot:
```{r}
#setup
idx <- seq(as.Date('1850-01-01'), as.Date('2018-11-01'), 'month')
idx <- as.yearmon(idx)
tmpplt <- setZ(hadcrut4, idx)
names(tmpplt) <- as.character(idx)
#plot
trellis.device('pdf', file = 'hov_hadcrut4.pdf')
hovmoller(tmpplt, dirXY=y,
at = do.breaks(c(-3.5,3.5),14),
contour = F, interpolate = F,
par.settings=RdBuTheme(region=rev(brewer.pal(9,'RdBu'))),
main="HadCRUT4 Anomalies 1850-2018 (1961-1990 base period)")
dev.off
```

Synchronized interactivity between two R plots (plotly and leaflet)

I’d like to synchronize the interactivity of two R plots: a plotly plot and a leaflet map. The plotly plot graphs a time series for a specific location in the leaflet map. In other words, I’d like to select a location (or group of locations) in a map and see the corresponding selection in the ploty plot and vice versa select a time series in the plotly plot and see the corresponding marker in the map highlighted. So, in both directions.
The attached file (dataset1) is a R list that contains all data. Each element of the list is a dataset (time series) for each location. The linked variable for both plots is “Codi.Estació”.
I’ve tried the crosstalk package but the authors warn that “Crosstalk currently only works for linked brushing and filtering of views that show individual data points, not aggregate or summary views”. I’m not interested in an individual data point but a whole time series.
Could anyone help me how to handle that? Tips, examples, other packages (instead of leaflet) are welcome?
Thank you very much and have a nice summer,
Download the dataset: https://drive.google.com/file/d/1PkPm1ObcEer8Lne5vJMZR6MdFTONRSvY/view?usp=sharing
Download HTML output: https://drive.google.com/open?id=1YHko4V-iAUZqZr3wNC7zGEdrMhjmykSA
The code in R Markdown (*.Rmd) (to run in Rstudio):
---
title: "Piezometers La Bisbal del Penedès "
author: "J.M. Campanera"
output:
flexdashboard::flex_dashboard:
orientation: columns
social: menu
---
```{r setup, include = FALSE}
library(plotly)
library(leaflet)
library(flexdashboard)
load("dataset1.RData")
```
Column {data-width=700}
-----------------------------------------------------------------------
### Water depth
```{r echo=FALSE}
# Plot 1
p<-plot_ly()
for (i in 1:length(dataset1)) {
p<-add_trace(p,name=dataset1[[i]]$Codi.Estació[1],x=dataset1[[i]]$Data,y=dataset1[[i]]$Valor,mode = 'scatter',type="scatter")
}
p
```
Column {data-width=300}
-----------------------------------------------------------------------
### well locations
```{r echo=FALSE}
m <- leaflet()
m<-addTiles(m)
for (i in 1:length(dataset1)) {
m<-addCircleMarkers(m,lng=dataset1[[i]]$Longitud[1], lat=dataset1[[i]]$Latitud[1],label=dataset1[[i]]$Codi.Estació[1],labelOptions = labelOptions(noHide = T, textOnly = TRUE),popup=as.character(dataset1[[i]]$Fondària.Pou..m.[1]))
}
m
```
Finally I develop a solution:
1) Interactivity in Plotly plot and highlighting in the leaflet map:
I used the funtion "event_data(event=c("plotly_click"))" and I get the inspiration from
https://plot.ly/r/shinyapp-plotly-events/
2) Interactivity in Leaflet map and highlighting in the plotly plot:
I used the funtion "input$map_marker_click" and I get the inspiration from here: https://rstudio.github.io/leaflet/shiny.html
Thank you,

2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!
NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

Resources