R tips

Here I present some R tips and tricks I have learned from various resources over the years.


demo(plotmath)

mat <- matrix(c("5","6","7","8","hello","world"),ncol=3)
class(mat) <- "numeric"

rmarkdown::render("source.Rmd")

source.Rmd

```{r}
args <- commandArgs(trailingOnly = TRUE)
args[1]+args[2]
```

command line

Rscript -e 'rmarkdown::render("source.Rmd")' 0.5 0.7

source.Rmd

---
output:
  html_document:
    toc: true
    theme: united
  knitrBootstrap::bootstrap_document:
    theme.chooser: TRUE
    highlight.chooser: TRUE
---

<!--
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{Some title here}
-->

Testing `knitrBootstrap`
==================================

```{r}
args <- commandArgs(trailingOnly = TRUE)
args[1]+args[2]
```

command line

Rscript -e 'library(knitrBootstrap);library(rmarkdown);render("source.Rmd", "knitrBootstrap::bootstrap_document")' .05 .07

be careful of the single quotes and double quotes: it matters!


"%ni%" <- Negate("%in%")
c(2,3) %ni% c(2,4,5)
[1] FALSE  TRUE


library(dplyr)

d <- Titanic %>% as.data.frame

(d1 <- d[1:5,])
  Class    Sex   Age Survived Freq
1   1st   Male Child       No    0
2   2nd   Male Child       No    0
3   3rd   Male Child       No   35
4  Crew   Male Child       No    0
5   1st Female Child       No    0

(d2 <- d[2:6,])
  Class    Sex   Age Survived Freq
2   2nd   Male Child       No    0
3   3rd   Male Child       No   35
4  Crew   Male Child       No    0
5   1st Female Child       No    0
6   2nd Female Child       No    0

anti_join(d1,d2, by=c("Class","Sex","Age"))
  Class  Sex   Age Survived Freq
1   1st Male Child       No    0

servr::jekyll(script = "_knitr/build.R", serve = FALSE)

If you get the following error:

Error in jekyll_build() : Failed to run: jekyll build

Try passing the full path of the executable jekyll to the servr::jekyll() function (which can be found via which jekyll in the terminal) as noted here. For example, on my laptop I ran the following command from the root directory of my website:

servr::jekyll(script = "_knitr/build.R", serve = FALSE, command = '/home/sahir/.rbenv/shims/jekyll build')

Sys.getenv("RSTUDIO_PANDOC")

To set the pandoc that you want it to use, enter the following in your .Renviron file (which should be in your $HOME directory):

RSTUDIO_PANDOC=/path/to/pandoc
comments powered by Disqus