Why does my R notebook produce a blank html document - knitr

For some reason, my R notebook is producing a blank HTML document. When I'm ready to knit the document to an html notebook, my browser opens up the file and it is a blank document. I'm pressing the "knit" button, then "html" from R Studio.
Here is my code:
---
title: "Rate Hole Model"
output: html_document
---
```{r}
library(tidyverse)
library(plotly)
library(rmarkdown)
library(knitr)
```
```{r}
veh_age <- mc2 %>%
filter(cummulative < 51)
plot_ly(veh_age, x = ~unit_age, y = ~loss_ratio, color = ~rating_class_name) %>%
add_markers(text = ~paste(rating_class_name, "<br />", 'unit age: ',
unit_age, "<br />", 'loss ratio: ', loss_ratio), hoverinfo =
'text') %>%
layout(title = 'Comp Loss Ratio by Unit Age/Rating Class')
```
I'm not sure what happened. I'm on R version 3.5.1Has anyone ran into this problem?

My Libraries were installed to my Home directory : \Home\firstname.lastname\documents. This directory is a network located resource. When the last step of the process ran, the proper permission was not available to the called application (Pandoc). I am running 64 bit Win 10 with 64 bit RStudio version 1.1.456 and the 3.5 version of R. When I moved (reinstalled) the packages/libraries to a local folder : c:\Program Files\RStudio\Packages the HTML rendered in the browser.

Related

i am trying to get a bokeh server to run, but when i type in the command in my terminal i get an error message

I am trying to run the code below in a bokeh server to visualize the plots. the final_imdb_dataframe is in the same directory as the python code. these are the steps i take to get the server to run:
open my terminal
type in "cd" then a space and then my directory in for the map containing my python script and the final_imdb_dataframe
press enter
type: bokeh serve --show "filename.py"
press enter
in my terminal i am getting this error message however:
bokeh : The term 'bokeh' is not recognized as the name of a cmdlet, function, script file, or operable program. (the complete error message is attached as a picture)
when i type in "pip show bokeh" in the command promt in python it gives me this:
pip show bokeh
Name: bokeh
Version: 2.4.3
Summary: Interactive plots and applications in the browser from Python
Home-page: https://github.com/bokeh/bokeh
Author: Bokeh Team
Author-email: info#bokeh.org
License: BSD-3-Clause
Location: c:\users\fazan\anaconda\lib\site-packages
Requires: Jinja2, numpy, packaging, pillow, PyYAML, tornado, typing-extensions
Required-by: hvplot, panel
Note: you may need to restart the kernel to use updated packages.
so it should work right?
i don't know what to do anymore...
code:
import pandas as pd
from bokeh.plotting import figure, show
import numpy as np
from bokeh.models import ColumnDataSource, HoverTool, Slider, RangeSlider, Div, Select
from bokeh.io import output_file, curdoc
from bokeh.layouts import column, row, layout
#EERSTE PLOT:
#line diagram of amount of movies released each year en avg rating displayed over the years
df = pd.read_csv("final_imdb_dataframe")
#"unnamed column weghalen
df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)
#creating plot 2
plot2 = figure(plot_width = 1000,
plot_height = 400,
x_axis_label= "year",
title = "watchtime and movie rating over the years")
#creating a dropdown menu
source2 = ColumnDataSource(data={'x': df["release_date"], 'y': df["watchtime"]})
plot2.circle(x="x", y="y", size = 3, source = source2, alpha = 0.2)
def update_plot(attr, old, new):
if new == 'watchtime':
source2.data = {'x' : df["release_date"], 'y' : df["watchtime"]}
else:
source2.data = {'x' : df["release_date"], 'y' : df["movie_rating"]}
select = Select(title = "keuze menu", options=["watchtime", "movie_rating"], value = 'watchtime')
#code for updating the plot when the value is changed
select.on_change('value', update_plot)
#TWEEDE PLOT:
#creating a list of all the years a movie came out
dfrelease = df.release_date.drop_duplicates().tolist()
#sorting the list with release dates to get them in chronological order
dfrelease1 = sorted(dfrelease)
#creating an empty list
total_releases_per_year = []
#adding the amount of movies that came out every year to the list
for i in range(len(dfrelease1)):
total_releases_per_year.append(len(df[df["release_date"] == dfrelease1[i]]))
#creating a columndatasource of the two lists created above to make it possible for the hovertool to be used
source1 = ColumnDataSource(data=dict(year = dfrelease1, amount_of_movies_made = total_releases_per_year))
#making a hovertool
hover2 = HoverTool(tooltips=[("year", "#year"), ("amount of movies made", "#amount_of_movies_made")])
#creating plot 3
plot3 = figure(plot_width = 1000,
plot_height = 400,
x_axis_label= "year",
y_axis_label = "amount of movies",
title = "amount of movies per year")
plot3.line("year", "amount_of_movies_made", source = source1)
plot3.add_tools(hover2)
#DERDE PLOT:
#creating the ColumnDataSource
df_sel = df[df["release_date"] == 2020]
source1 = ColumnDataSource(df_sel)
#scatter plot
p1 = figure(title = "relation 'watchtime' and 'movie rating' over the years",
x_axis_label= "watchtime",
y_axis_label= "rating (0-10)",
plot_width = 1000,
plot_height = 400)
p1.circle(x="watchtime", y="movie_rating", alpha = 0.2, source=source1)
#making the rangeslider
slider = RangeSlider(title="release date", value= (1919, 2021), start=1919, end=2020, step=1)
#making the hover tool
hover1 = HoverTool(tooltips=[("title", "#movie_name"),("gross", "#gross_collection"),("votes", "#votes"),("genre", "#genre"), ("watchtime", "#watchtime"),("rating", "#movie_rating"),("release date", "#release_date")])
#making a def callback for the rangeslider to work when moved
def callback(attr, old, new):
year = slider.value
source1.data = df[(df["release_date"] >= year[0]) & (df["release_date"] <= year[1])]
slider.on_change("value", callback)
layout = column(slider, p1) #create a layout with slider on top of plot
p1.add_tools(hover1) #adding hover tool
layout3 = column(select, plot2, plot3, slider, p1) #making the layout for the dashboard
curdoc().add_root(layout3)*
i tried what i wrote above and expected acces to the bokeh server that would show me my plots. i have done this before on my previous computer (mac) and it worked then. now on my lenovo it is not working.`

leaflet map not rendering in html document using rmarkdown

Here is my code
---
date: "7 December 2018"
output: html_document
---
## 7 December 2018
```{r, echo=FALSE}
library(leaflet)
library(jsonlite)
citibike <- fromJSON("http://citibikenyc.com/stations/json")
stations <- citibike$stationBeanList
m = leaflet(stations) %>% addTiles(urlTemplate = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') %>% addCircles(lat = ~latitude, lng = ~longitude, weight = 5, radius = ~availableBikes, popup = paste("Station:", stations$stationName, "<br>", stations$availableBikes, "available bikes", "<br>", stations$availableDocks, "available docks")) %>% addControl("Available Bikes in NYC on 12/07/2018", position = "topright")
m
```
Using Knit, the html document created only shows the date but not the map. The map is created without any problem when using that code in the console of RStudio.
I have downloaded the latest version of leaflet from github. I use Windows 10.
platform x86_64-w64-mingw32 arch x86_64
os mingw32 system x86_64,
mingw32 status major
3 minor 5.1
year 2018 month 07
day 02 svn rev 74947
language R version.string R version
3.5.1 (2018-07-02) nickname Feather Spray

Fitting custom functions to data

I have a series of data, for example:
0.767838478
0.702426493
0.733858228
0.703275979
0.651456058
0.62427187
0.742353261
0.646359026
0.695630431
0.659101665
0.598786652
0.592840135
0.59199059
which I know fits best to an equation of the form:
y=ae^(b*x)+c
How can I fit the custom function to this data?
Similar question had been already asked on LibreOffice forum without a proper answer. I would appreciate if you could help me know how to do this. Preferably answers applying to any custom function rather than workarounds to this specific case.
There are multiple possible solutions for this. But one approach would be the following:
For determining the aand b in the trend line function y = a*e^(b*x) there are solutions using native Calc functions (LINEST, EXP, LN).
So we could the y = a*e^(b*x)+c taking as y-c= a*e^(b*x) and so if we are knowing c, the solution for y = a*e^(b*x) could be taken too. How to know c? One approach is described in Exponential Curve Fitting. There approximation of b, a and then c are made.
I have the main part of the delphi code from Exponential Curve Fitting : source listing translated to StarBasic for Calc. The part of the fine tuning of c is not translated until now. To-Do for you as professional and enthusiast programmers.
Example:
Data:
x y
0 0.767838478
1 0.702426493
2 0.733858228
3 0.703275979
4 0.651456058
5 0.62427187
6 0.742353261
7 0.646359026
8 0.695630431
9 0.659101665
10 0.598786652
11 0.592840135
12 0.59199059
Formulas:
B17: =EXP(INDEX(LINEST(LN($B$2:$B$14),$A$2:$A$14),1,2))
C17: =INDEX(LINEST(LN($B$2:$B$14),$A$2:$A$14),1,1)
y = a*e^(b*x) is also the function used for the chart's trend line calculation.
B19: =INDEX(TRENDEXPPLUSC($B$2:$B$14,$A$2:$A$14),1,1)
C19: =INDEX(TRENDEXPPLUSC($B$2:$B$14,$A$2:$A$14),1,2)
D19: =INDEX(TRENDEXPPLUSC($B$2:$B$14,$A$2:$A$14),1,3)
Code:
function trendExpPlusC(rangey as variant, rangex as variant) as variant
'get values from ranges
redim x(ubound(rangex)-1) as double
redim y(ubound(rangex)-1) as double
for i = lbound(x) to ubound(x)
x(i) = rangex(i+1,1)
y(i) = rangey(i+1,1)
next
'make helper arrays
redim dx(ubound(x)-1) as double
redim dy(ubound(x)-1) as double
redim dxyx(ubound(x)-1) as double
redim dxyy(ubound(x)-1) as double
for i = lbound(x) to ubound(x)-1
dx(i) = x(i+1) - x(i)
dy(i) = y(i+1) - y(i)
dxyx(i) = (x(i+1) + x(i))/2
dxyy(i) = dy(i) / dx(i)
next
'approximate b
s = 0
errcnt = 0
for i = lbound(dxyx) to ubound(dxyx)-1
on error goto errorhandler
s = s + log(abs(dxyy(i+1) / dxyy(i))) / (dxyx(i+1) - dxyx(i))
on error goto 0
next
b = s / (ubound(dxyx) - errcnt)
'approximate a
s = 0
errcnt = 0
for i = lbound(dx) to ubound(dx)
on error goto errorhandler
s = s + dy(i) / (exp(b * x(i+1)) - exp(b * x(i)))
on error goto 0
next
a = s / (ubound(dx) + 1 - errcnt)
'approximate c
s = 0
errcnt = 0
for i = lbound(x) to ubound(x)
on error goto errorhandler
s = s + y(i) - a * exp(b * x(i))
on error goto 0
next
c = s / (ubound(x) + 1 - errcnt)
'make y for (y - c) = a*e^(b*x)
for i = lbound(x) to ubound(x)
y(i) = log(abs(y(i) - c))
next
'get a and b from LINEST for (y - c) = a*e^(b*x)
oFunctionAccess = createUnoService( "com.sun.star.sheet.FunctionAccess" )
args = array(array(y), array(x))
ab = oFunctionAccess.CallFunction("LINEST", args)
if a < 0 then a = -exp(ab(0)(1)) else a = exp(ab(0)(1))
b = ab(0)(0)
trendExpPlusC = array(a, b, c)
exit function
errorhandler:
errcnt = errcnt + 1
resume next
end function
The formula y = beax is the exponential regression equation for LibreOffice chart trend lines.
LibreOffice exports all settings
All the settings of LibreOffice, all in the LibreOffice folder.
C:\Users\a←When installing the operating system, the name
entered.\AppData←File Manager ~ "Hidden project" to open, the AppData
folder will be displayed.\Roaming\LibreOffice
Back up the LibreOffice folder, when reinstalling, put the LibreOffice folder in its original place.
Note:
1. If the installation is preview edition, because the name of preview edition is LibreOfficeDev, so the LibreOfficeDev folder will be
displayed.
2. Formal edition can be installed together with preview edition, if both formal edition and preview edition are installed, LibreOffice
folder and LibreOfficeDev folder will be displayed.
3. To clear all settings, just delete the LibreOffice folder, then open the program, a new LibreOffice folder will be created.
LibreOffice exports a single toolbar I made
Common path
C:\Users\a←When installing the operating system, the name
entered.\AppData←File Manager ~ "Hidden project" to open, the AppData
folder will be
displayed.\Roaming\LibreOffice\4\user\config\soffice.cfg\modules\Please
connect the branch path of the individual software below.
Branch path
\modules\StartModule\toolbar\The "Start" toolbar I made is placed here.
\modules\swriter\toolbar\The "writer" toolbar I made is placed here.
\modules\scalc\toolbar\The "calc" toolbar I made is placed here.
\modules\simpress\toolbar\The "impress" toolbar I made is placed here.
\modules\sdraw\toolbar\The "draw" toolbar I made is placed here.
\modules\smath\toolbar\The "math" toolbar I made is placed here.
\modules\dbapp\toolbar\The "base" toolbar I made is placed here.
Backup file, when reinstalling, put the file in the original place.
Note:
Because of the toolbar that I made myself, default file name, will automatically use Numbering, so to open the file, can know the name of
the toolbar.
The front file name "custom_toolbar_" cannot be changed, change will cause error, behind's file name can be changed. For example:
custom_toolbar_c01611ed.xml→custom_toolbar_AAA.xml.
Do well of toolbar, can be copied to other places to use. For example: In the "writer" Do well of toolbar, can be copied to "calc"
places to use.
LibreOffice self-made symbol toolbar
Step 1 Start "Recording Macros function" Tools\Options\Advanced\Enable macro recording(Tick), in the
"Tools\Macros", the "Record Macro" option will appear.
Step 2 Recording Macros Tools\Macros\Record Macro→Recording action (click "Ω" to enter symbol→select symbol→Insert)→Stop
Recording→The name Macros stored in "Module1" is Main→Modify Main
name→Save.
Step 3 Add item new toolbar Tools\Customize\Toolbar→Add→Enter a name (example: symbol)→OK, the new toolbar will appear in the top
left.
Step 4 Will Macros Add item new toolbar Tools\Customize\Toolbar\Category\Macros\My
Macros\Standard\Module1\Main→Click "Main"→Add item→Modify→Rename (can
be named with symbol)→OK→OK.

Using tikz graphdrawing library within RMarkdown ... Need to use lualatex engine, but can't get it to work

I have the following code in an rmd file which leverages tikz for diagrams:
---
title: "TestNonTufteLua"
author: "Me"
output:
pdf_document :
latex_engine: lualatex
---
Prove tikz works:
```{r tikTest1, engine = "tikz"}
\usetikzlibrary{shapes}
\begin{tikzpicture}
\node[ellipse, draw=black, align = center] (Data) {Data $y_{n}$};
\end{tikzpicture}
```
Then, when you set `eval = TRUE` in the below code, it will not work.
```{r tikTest2, eval = FALSE, engine = "tikz"}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
When changing to eval=TRUE in the second chunk, I get the following
error:
Quitting from lines 24-29 (testNonTufteLua.Rmd) Error: running
'texi2dvi' on '.\tikz36747a021b22.tex' failed
LaTeX errors: rarygraphdrawing.code.tex:22: Package pgf Error: You
need to run LuaTeX to use the graph drawing library.
This error occurs when using the knit button from RStudio or using render("testNonTufteLua.Rmd", output_format = pdf_document(keep_tex = TRUE, latex_engine = "lualatex"). I have also experimented with setting options(tikzDefaultEngine = "luatex") to get tikzDevice to handle it properly, but it still does not work. I just can't seem to get the graphdrawing library to work even though the tikz-shapes library can be loaded and also that the rest of the document seems to be compiled with lualatex. Thanks for any help!!
Update: Meanwhile knitr no longer uses tools::texi2dvi but tinytex::latexmk. One therefore has to use options(tinytex.engine = 'lualatex') in a set-up chunk.
This is rather tricky, since you are not using tikzDevice but the tikz engine, which uses tools::texi2dvi to convert to PDF. You can change this using options(texi2dvi = "lualatex"). However, the default template does not work with LuaLaTeX. I have therefore created a modified template:
\RequirePackage{luatex85}
\documentclass{article}
\usepackage[luatex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
And specify that file with engine.opts = list(template = "tikz2pdf.tex"). Putting it all together here my working file:
---
title: "TestNonTufteLua"
author: "Me"
output:
pdf_document :
latex_engine: lualatex
---
```{r}
options(texi2dvi = "lualatex")
```
```{r tikTest2, eval = TRUE, engine = "tikz", engine.opts = list(template = "tikz2pdf.tex")}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
Result:
References:
how to set engine options
preview and LuaLaTeX
knitr using texi2pdf
A small running variation of the example above is the following using tinytex.
---
title: "lualatex. Using `tinytex.engine`"
output:
html_document:
df_print: paged
pdf_document:
latex_engine: lualatex
---
## Latex engines
By default, PDF documents are rendered using `pdflatex`. You can specify an
alternate engine using the `latex_engine` option. Available engines
are `pdflatex`, `xelatex`, and `lualatex.`
```{r setup}
options(tinytex.engine = "lualatex")
```
```{r tikzLua, eval = TRUE, engine = "tikz", engine.opts = list(template = "tikz2pdf.tex")}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
After an update in knitr the example above stopped running.

htmlTable in Rmd - conversion to Word docx

I have the following Rmd file, which produces an html file, which I then copy-paste into a docx file (for collaborators). Here are things I'd like to know how to do with the tables, but I can't find answers in the vignettes here:
A. I want to know how to remove the blank column that gets inserted in Word in between Cgroup 1 and Cgroup 2.
B. I want to know how to set the width of the column with the row names ("1st row",...)
C. How can I change the font and font size? I tried following this but it doesn't work to have output: word_document with htmlTable()
D. To ease the conversion to Word, is there a way to specify page breaks? Landscape orientation?
Thank you so much!
---
title: "Example"
output:
Gmisc::docx_document:
fig_caption: TRUE
force_captions: TRUE
---
Results
=======
```{r, echo = FALSE}
library(htmlTable)
library(Gmisc)
library(knitr)
mx <-
matrix(ncol=6, nrow=8)
rownames(mx) <- paste(c("1st", "2nd",
"3rd",
paste0(4:8, "th")),
"row")
colnames(mx) <- paste(c("1st", "2nd",
"3rd",
paste0(4:6, "th")),
"hdr")
for (nr in 1:nrow(mx)){
for (nc in 1:ncol(mx)){
mx[nr, nc] <-
paste0(nr, ":", nc)
}
}
htmlTable(mx,
cgroup = c("Cgroup 1", "Cgroup 2"),
n.cgroup = c(2,4))
```
The styling seemed to be off for the row names and it is now fixed in version 1.10.1 that you can download using the devtools package: devtools::install_github("gforge/htmlTable", ref="develop")
Regarding the styling the function allows almost any CSS-style you could image. Unfortunately it requires copy-pasting into Word and this functionality hasn't been Microsofts highest priority. You can easily adapt you example to accomodate the requiered changes using the css.cell:
library(htmlTable)
library(knitr)
mx <-
matrix(ncol=6, nrow=8)
rownames(mx) <- paste(c("1st", "2nd",
"3rd",
paste0(4:8, "th")),
"row")
colnames(mx) <- paste(c("1st", "2nd",
"3rd",
paste0(4:6, "th")),
"hdr")
for (nr in 1:nrow(mx)){
for (nc in 1:ncol(mx)){
mx[nr, nc] <-
paste0(nr, ":", nc)
}
}
css.cell = rep("font-size: 1.5em;", times = ncol(mx) + 1)
css.cell[1] = "width: 4cm; font-size: 2em;"
htmlTable(mx,
css.cell=css.cell,
css.cgroup = "color: red",
css.table = "color: blue",
cgroup = c("Cgroup 1", "Cgroup 2"),
n.cgroup = c(2,4))
There is no way to remove the empty column generated by cgroups. This was required for the table to look nice and is a conscious design choice.
Regarding page-breaks I doubt there is any elegant way for doing that. An alternative could possibly be the ReporteRs package. I haven't used it myself but it's closer integrated with Word and could possibly be a solution.