Skip to content

Instantly share code, notes, and snippets.

@rmflight
Last active July 24, 2020 00:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rmflight/bb61ad1fd8ba6e44f734 to your computer and use it in GitHub Desktop.
Save rmflight/bb61ad1fd8ba6e44f734 to your computer and use it in GitHub Desktop.
stuff I always need to find

If you want to know how many lines of code are in an Rmd file:

rmarkdown::render("file.Rmd", output_format = "md_document")

cat file.md | grep -c '^ \{4\}'

And then how many lines of code in .R files:

wc --lines file.R

Get an error about X11 Missing font

X11 font -adobe-helvetica-%s-%s-*-*-%d-*-*-*-*-*-*-*, face 1 at size 12 could not be loaded

The solution is:

X11.options(type = "cairo")

Want to use a particular font in a graphic

For example, to add a Monospaced font to a graphic instead of a proportional font:

library(showtext)
font.add("FreeMono", "FreeMono.ttf")
showtext.auto()

Cairo("graphic.png", width = 2600, height = 3600, dpi = 300, bg = "#FFFFFF", fontfamily = "FreeMono")
plot(..., gpar(fontsize = 24, fontfamily = "FreeMono"))
dev.off()

rJava: can't load .so object

R CMD javareconf -e

Restart R / RStudio (i.e. complete shutdown and restart)

rJava, no jni.h

If you've confirmed that jni.h can be found, and that

R CMD javareconf -n

still shows an error, and it seems to be mainly due to using the incorrect directory for JAVA, one solution may be to make a link from the directory R wants to use, to the actual one.

sudo ln /usr/lib/jvm/right_java_dir /usr/lib/jvm/wrong_java_dir

working with temp temp directories

create_in_temp <- function(dir_loc, create_it = TRUE) {
  temp_path <- tempfile(pattern = paste0("copyfiles-test-", dir_loc))
  if (create_it) {
    dir.create(temp_path)
  }
  temp_path
}
erase <- function(path) unlink(path, recursive = TRUE)

skipping tests conditionally

  • in ci have export skip_variable=TRUE
skip_variable <- as.logical(Sys.getenv("skip_variable"))
if (is.na(skip_variable)) {
  skip_variable <- FALSE
}

test_that("test we want to skip conditionally", {
  skip_if_not(skip_variable)
  expect_true(test condition)
})

test_that("other tests", {

})

ComplexHeatmap

Modify the font sizes in the heatmap

If you want to get the font sizes right for a plot, you will need to play with these font sizes

# add the following, add col* if you want to modify both
row_names_gp = gpar(fontsize = 24, fontfamily = "FreeMono")

Saving a PNG

Cairo("filename", width = 2600, height = 6210, dpi = 300, bg = "#FFFFFF", fontfamily = "FreeMono")
Heatmap(heatmap, colormap, "Expression", cluster_rows = FALSE, cluster_columns = FALSE, row_names_gp = gpar(fontsize = 24, fontfamily = "FreeMono"), column_names_gp = gpar(fontsize = 30))
dev.off()

ggplot2

Rotate axis tick labels 90 degrees

+ theme(axis.text.x = element_text(angle = 90))

Remove the legend

+ theme(legend.position="none")

Make COWPLOT fontsize a bit bigger

mod_theme <- theme_cowplot(font_size = 16)
theme_set(mod_theme)

Make PNG of high-density SVGs

SVG is great for posters, can resize at will. But if there are a lot of points, then we really want PNG. This workflow we export the point figure to SVG at the set size, and then convert to PNG using InkScape at the command line.

ggsave("filename.svg", plot_to_save)
system("inkscape -z -d 300 -e outfile.png infile.svg")

Include cowplot in package deps

If we want to use the cowplot theme, but keep from generating warnings, etc in R CMD check of when loading the package, then we should structure things like so:

#' @import ggplot2

theme_set(cowplot::theme_cowplot())

And in DESCRIPTION:

imports: ggplot2, cowplot

Inkscape

Add a bullet

ctrl+u, 2022, enter

Flow Text Around an Object

  • Draw a path around the object using whatever tool you want
  • Select the previous written text's box
  • Select the path object
  • Text -> Flow into Frame

Random Forest

Separability plot

Use cmdscale on the proximities to look at how the samples behave in RF.

# generate model
rf_model <- randomForest(x ...., proximity = TRUE)
# generate MDS scaling of proximities
rf_sep <- stats::cmdscale(1 - rf_model$proximity, k = 2, eig = TRUE) # two components, using eigenvalue based 
# data.frames are nicer to work with, but just need the points from cmdscale
rf_sep <- as.data.frame(rf_sep$points)
names(rf_sep) <- c("dim1", "dim2")

# add your class information so can see how classes behave relative to one another using coloring (or shape, etc)
rf_sep$class <- factor_of_classes

ggplot(rf_sep, aes(x = dim1, y = dim2, color = class)) + geom_point()

Install Specific Bioconductor Package Versions

Easily switch between fraction and number of things

correctly_round_numbers <- function(number_of_things, fraction){
  assertthat::assert_that(number_of_things > 0)
  if (fraction < 1) {
    floor_value <- floor(number_of_things * fraction)
  } else {
    floor_value <- number_of_things
  }
  floor_value
}

Anonymize Things While Retaining Order

Courtesy of David Robinson

as.integer(fct_inorder(x))
library(ReporteRs)
doc <- pptx()

p <- ggplot() ....

doc <- addSlide(doc, slide.layout = "Content with Caption")
doc <- addPlot(doc = doc, fun = print, x = p, vector.graphic = TRUE)

writeDoc(doc = doc, file = "file.pptx")
---
title: "a good title"
author: "Robert M Flight"
date: "`r Sys.time()`"
commit: "`r substr(git2r::branch_target(git2r::head(git2r::repository())), 1, 8)`"
output: 
  pdf_document: 
    toc: yes
---

Knitr chunk setup

{r setup, echo=FALSE}
knitr::opts_chunk$set(cache = TRUE, warning = FALSE, message = FALSE)

Data Checking

library(assertthat)
library(assertr)

Packages Used

pkg_info <- devtools::session_info()
pkg_info$platform
knitr::kable(pkg_info$packages)

Wide Format PDF Tables in RMarkdown

---
header-includes:
  - \usepackage{longtable} # allows use of tables spanning pages
  - \usepackage{caption} # used if you need to define your own captions
  - \captionsetup{labelformat = empty} # for empty captions
output: pdf_document
classoption: landscape # turns output to landscape
---
out_table <- xtable::xtable(df, type = "latex")
xtable::caption(tmp_table) <- "caption text"
xtable::align(out_table) <- "llp{2in}ll" # assuming 4 column table, second column would only take up 2 inches of space
print(out_table, comment = FALSE, floating = FALSE, tabular.environment = "longtable") # important at end, to make sure that the environment is correct, because otherwise the tables won't display right, believe me

Setting Parameters

parameters = read_delim(

'Parameter     | Value | Units 
#--------------|-------|-------
 herd_size     | 20.00 | camels
 max_age       | 25.00 | years
 fertile_age   |  5.00 | years ',
 
 delim = '|', trim_ws = TRUE, comment = "#')
 
input = structure(as.list(parameters$Value),
                  names = parameters$Parameter)
kable(parameters, align = c('l', 'r', 'l'), caption = 'Model Parameters')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment