choose working directory in code option of r chunk - r

So I am using RMarkdown and I am sourcing code from a script contained in a separate folder (Scripts) at the same level as the folder which contains the Markdown file (Report). Both directories are at the root of the R project.
I achieve that first by setting the working directly using the following code in the setup chunk:
knitr::opts_knit$set(root.dir = normalizePath(".."))
Then calling the following in a R chunk:
```{r datacreation, echo = FALSE}
source("./Scripts/20212022Summary.R")
```
All that is great but I also want to display later on in the knitted document, the whole code contained in that script so it can be reviewed if necessary.
To achieve this, I do :
```{r 20212022Summary_readlinesversion, code = readLines("../Scripts/20212022Summary.R"),echo=TRUE,include = knitr::is_html_output(),cache=FALSE,eval = FALSE}```
Which just shows the code without running it, with a nice formatting.
What I would like to know is how I would go about defining once and for all what is my working directory for consistency sake. Specifically when I call code = readLines("../Scripts/20212022Summary.R") I clearly operate with the knowledge it will consider the working directory to be the one containing the report instead of the one (parent directly aka project root directory) which I defined previously in the set up chunk.
Ideally I would define things once and for all, especially as then I could pick those up programmatically and source from anywhere within the project folder, consistently.
Anyone has tips on how to achieve this? What I have done works, it's just ugly, manual and not consistent. And it bugs me :)

Related

Is there a global command line knit option as eval=FALSE for all chunks?

I quite often make mistakes in the text part of *.Rmd documents and, in some cases,
fixing and running knit() implies re-running R commands that can take a while.
Therefore, it is an advantage running the .Rmd document without actually executing the R code first, then fix any typos and structure errors and then run again with evaluation.
I know this can be achieved by including
knitr::opts_chunk$set(eval = FALSE)
in the .Rmd
but I would prefer avoiding to actually edit the .Rmd file and using an equivalent way at the command line, something like
knit("file.Rmd", eval=FALSE)
Is actually there a way to achieve this at the command line?
You do not need to edit the .Rmd file. You can just run
knitr::opts_chunk$set(eval = FALSE)
before running knitr::knit(); knitr will respect the global chunk options you set before calling knitr::knit().
I think you might consider to add cache=TRUE to the options in knitr, that will avoid running again the code chunk again if you didn't change anything within it.
https://bookdown.org/yihui/rmarkdown-cookbook/cache.html
You can get a general effect if you add this at the beginning of the .Rmd file, like for example:
knitr::opts_chunk$set(echo = TRUE, cache = TRUE)

Setting Rmd directory

I'm new to R. I usually work my projects in a setting characterized by a directory in which I assign datasets, code and graphics specific folders. This is:
Main directory ~Project
Code ~Project\Code
Within my setup chunk I declare:
knitr::opts_knit$set(root.dir = "~Project")
knitr::opts_knit$get("root.dir")
However, in any following chunk where, for example I wish to load a dataset stored in 'Data' folder as:
read.csv("Data/series.csv",header=TRUE,check.names=FALSE)
I get a warning message on failure to find such directory.
Any advice? Thank you very much!
You need a ".." before that to tell R Studio first to go up a level (to the main directory):
read.csv("../Data/series.csv",header=TRUE,check.names=FALSE)
If you want to check what directory you're in, try running code like print(getwd()) in your chunk.
It's also not clear whether your error comes when you try to knit the document, or just when working on the Project; that does make a difference.

How do I assign the working directory for rmarkdown/knitr interactive doc on shinyApps.io?

I have a fully functional interactive shiny doc using knitr/r markdwon.
However, when I try to publish (deploy) it to shinyApps.io, I get an error saying the .PNG file I try to incorporate into the doc (using readPNG from the png package) is unable to open.
I know the problem is related to working directories.
In my original code I assigned a working directory to my folder (i.e., "C:/Users/NAME/documents/...." that contains both my .rmd file and my .png file. However, obviously my folder doesn't exist on the shinyapps.io.
So how exactly do I set my working directory to open the .png file via my doc on shinyapps.io?
I can't find anywhere that explicitly walks through this process. Please help explain this simply/basically for me.
Example:
Assume I have a folder in "C:/Users/NAME/documents/Shiny" that contains 2 files: "shiny.rmd" and "pic.png". I want "pic.png" to be rendered in my shiny.rmd doc.
Currently I have:
---
title: "TroubleShoot"
output: html_document
runtime: shiny
---
```{r ,echo=FALSE,eval=TRUE}
library(png)
library(grid)
direct <- "C:/Users/NAME/documents/Shiny/"
img <- readPNG(paste0(direct,"pic.PNG"))
grid.raster(img)
```
How do I rewrite my code so it works on shinyApps.io?
Do I need to create and name folders in specific ways to place my 2 files into before deploying?
When you paste the c drive to direct, and read the direct into img, you are sending the app/markdown to your local drive. You need to use a relative path to the project. I would suggest something like:
direct <- "./"
Which uses the relative path, not the absolute path.
That said you might be able to skip that step entirely if the .png is in the same folder as the shiny object. just call the file name and format and leave it as that.
Also, check you use of ". Your syntax highlighting indicates your code won't run properly as it thinks some of your functions and variables are character strings because you've misplaced your quotes around read.png(). That's probably just a copy and paste typo though.
In summary, call the image via grid.raster("./pic.PNG"), and brush up on how working directories and relative paths work.
In the absence of knowing exactly how you're 'setting' your working directory:
In rStudio to correct and easiest approach is to make a 'New Project' for every New Project. You can do this as the first step in your project, or you can add a project file to an existing directory.
When you do this it automatically sets your working directory correctly. The way you seem to be doing it is not correct, you are merely supplying a 'path'. If you were to not want to use a project for some reason (I can't think of a case where that would be right), then you can always use setwd(), however, I believe this needs to be used in every session. A true project doesn't have that requirement.
This will then allow you to deploy your app properly as it will update the working directory to the one on the host machine at shinyapps.io when it is initialised there.
Finally, using the correct relative syntax "./path/to/my.file" to reference all your assets, images, data etc, should correct your issue as stated in the question.

slidify lectureSite: workflow and customizations

I am getting started with http://slidify.github.io/lectureSite/. I like the idea and the template very much. However, being new to this, I am struggling with customization.
Let me first explain what this 'lectureSite' architecture offers. The main code is based on rmarkdown and slidify and the customizations of the layout are mainly controlled in css files. The 'lectureSite' consists of an html webpage that serves as a contents page and starting point to access different slides ('lectures'), much of it created automagically. It looks as great as it sounds!
Each lecture is stored in a separate directory with its own 'assets' directory. So in a course made of 10 lectures, one has 10 directories, each with its own css and js. However, to achieve a common style for the whole course, one would like most of the customizations to be shared among all the lectures. My main problem is how to deal with this.
Question: How should I deal with the css customizations that I would like to share among all the lectures?
I have been successful in customizing each lecture by inserting the css code into each rmarkdown file between <style> and </style> tags, but now I would like to take the customizations to a place where they may be shared. I expected that by including a slidify.css file inside assets/css the styles would be picked up, but they are not: could I be doing something wrong or was my expectation incorrect to begin with? And besides, there are so many of those assets/css directories that it would be tedious to have to copy the css into each every time it is modified. Is there a mechanism to set a single css file that would override the css inside assets/css?
I also tried to make a 'declaration' at the top of the rmarkdown file (something I saw there: http://rmarkdown.rstudio.com/html_document_format.html) with:
css : slidify.css
but that gave the following error message:
pandoc: Could not fetch slidify.css
slidify.css: openBinaryFile: does not exist (No such file or directory)
Error: pandoc document conversion failed with error 67
Execution halted
An alternative would be to source() a text file with the customization between <style> and </style> tags. Are there any disadvantages to this approach? And btw what is the code for sourcing an external file from rmarkdown?
Consider the following structure:
assets -> put custom img/js/css/layout assets
lectures -> folder containing lectures
Lecture 01
Lecture 02
Lecture 03
libraries -> frameworks, highlighters and widgets
index.Rmd -> Rmd source for home page
site.yml -> Site related configuration
and suppose you are inside one of the Lectures index.Rmd files. I found the following seems to 'by-pass' the local assets directory to source the 'root' directory instead:
url : {lib: "../../libraries", assets: "../../assets"}
If you place your css files into "../../assets/css/custom.css", that is the 'master' assets directory at the top of the structure (at the root, to say it differently), then it will be sourced by slidify. I deleted all the other assets directories and didn't find it did any harm (all they contained to begin with was one single file ribbons.css). Not extensively tested, but it worked on Firefox and Chrome.
In this way, I can have a single customization css for all the chapters.
However, this structure appears to work only for the html5slides framework and not for io2012. For io2012 I explain here what I did (it worked for me, but I have no idea if it's the right way):
https://github.com/ramnathv/slidify/issues/409
Somewhat more involved. Hopefully future versions of slidify will make it easier. One problem with dumping style files into the root assets directory is that, with the html5slides framework, all files are sourced. So my idea of having framework-specific css files in the assets directory doesn't work, because the styles are all sourced and some overwrite one another. So keeping the custom css files in framework-specific directories is probably a better approach anyhow.
I also found the following way of sharing R customizations and knit opts (or whatever they're called)
```{r 'preamble', message = FALSE, warning = FALSE, error = FALSE, echo = FALSE, tidy = FALSE, comment = NA, cache = FALSE} # probably several redundant ones in there
require(knitr)
opts_chunk$set(echo = FALSE, cache = FALSE) # example of knit options
source('../../shared/shared.R') # here I share common R code
```

How to display images in Markdown on github generated from knitr without using external image hosting?

I like uploading repositories to github that include multiple R Markdown and Markdown files.
Here is an example of such a markdown file on github. And here's a screen grab.
The problem is that images do not display. You can click on the image, and you will go to where the file is stored.
The file referenced is:
https://github.com/... /blob/.../myfigure.png
whereas I presume it needs to reference
https://github.com/... /raw/.../myfigure.png
Things I considered:
imgur: I could use external image hosting (e.g., see this example) by adding the following code:
```{r setup}
opts_knit$set(upload.fun = imgur_upload) # upload all images to imgur.com
````
However, for various reasons I don't want to do this (I have trouble uploading when behind a firewall; it's slow; it creates an unnecessary dependency)
Rpubs: There's also RPubs which is quite cool. However, at time of posting it seems more suited to single markdown documents rather than multiple R markdown documents. And it doesn't provide such a close link between source R Markdown and the Markdown document.
Question
Is there a workflow for using R Markdown and knitr to produce Markdown files which when uploaded to github permit the Markdown file to display images stored in the github repository?
This used to be part of the minimal example, use
opts_knit$set(base.url='https://github.com/.../raw/.../')
See the changes here and here.
Also see http://yihui.name/knitr/options.
EDIT [with update to restore base.url to former value
Regarding switching, you could define a function as
create_gitpath <- function(user, repo, branch = 'master'){
paste0(paste('https://github.com', user, repo, 'raw', branch, sep = '/'),'/')
}
my_repo <- create_gitpath(user, repo)
knit.github <- function(..., git_url ){
old_url <- opts_knit$get('base.url')
on.exit(opts_knit$set(base.url = old_url))
opts_knit$set(base.url = git_url)
knit(..., envir = parent.frame())
}
Run with knit until you want to push to github then run knit.github(..., git_url = my_repo)
What about the following code at the beginning of your markdown file?
``` {r setup,echo=FALSE,message=FALSE}
gitsubdir <- paste(tail(strsplit(getwd(),"/")[[1]],1),"/",sep="")
gitrep <- "https://github.com/mpiktas/myliuduomenis.lt"
gitbranch <- "master"
opts_knit$set(base.url=paste(gitrep,"raw",gitbranch,gitsubdir,sep="/"))
```
It is possible to tweak it so that gitrep and gitbranch will be reported by git. Here I assumed that I am one directory level below the main git repository directory. Again this might be tweaked to accommodate more complicated scenarios.
I've tested on github, here is the Rmd file and corresponding md file.

Resources