Created
June 8, 2022 18:57
-
-
Save Sejmou/dfc5424a924edc1b279a5173e2ef6baf to your computer and use it in GitHub Desktop.
R Studio snippets (to use, copy into respective snippet file accessible via "Tools -> Edit Code Snippets...")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
snippet imfn | |
```{r, echo=F} | |
# This is a custom function I wrote for showing images | |
# It is more robust than embedding images in R markdown directly | |
# With imgs embedded in R markdown, compilation of whole document fails if img missing | |
# This function also displays the image if possible and just logs an error otherwise | |
# Under the hood, knitr::include_graphics() is used, which also accepts multiple image paths as parameter | |
# Therefore, with this function, side-by-side images are also supported | |
# We then need to pass a vector of paths in the function call and add fig.show='hold' to the code cell | |
# Be sure to also set out.width accordingly! (still per image) | |
# details: https://stackoverflow.com/a/54870008/13727176 | |
showimg <- function(paths, add = FALSE) { | |
invalid_imgs <- FALSE | |
for (path in paths) { | |
if (!file.exists(path)) { | |
message(paste0("cannot show image: file '", path, "' not found")) | |
invalid_imgs <- TRUE | |
} | |
} | |
if (!invalid_imgs) { | |
knitr::include_graphics(paths) | |
} | |
} | |
``` | |
snippet imadd | |
```{r, echo=F, out.width='80%', fig.align='center'} | |
showimg("./${1:file_name}") | |
``` | |
snippet imsadd | |
```{r, echo=F, fig.show='hold', out.width='45%', fig.align='center'} | |
showimg(c("./${1:file_name1}", "./${2:file_name2}")) | |
``` | |
snippet pm | |
```{r} | |
if (!require(pacman)) install.packages('pacman') | |
library(pacman) | |
``` | |
snippet pml | |
```{r} | |
p_load(${1:packages}) | |
``` | |
snippet r | |
```{r} | |
${1:code} | |
``` | |
snippet rne | |
```{r, eval=FALSE} | |
${1:code} | |
``` | |
snippet nonr | |
``` | |
${1:code} | |
``` | |
snippet _ | |
| |
snippet opts | |
```{r, setup, include=FALSE} | |
knitr::opts_chunk\$set( | |
comment = '' | |
) | |
``` | |
snippet c | |
`${1:inline_code}` $2 | |
snippet l | |
[`${1:link_text}`](${2:link}) $3 | |
snippet lc | |
[`${1:code}`](${2:link}) $3 | |
snippet fn | |
`${1:function_name}()` $2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
snippet in | |
%in% | |
snippet split_code | |
``` | |
```{r} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment