Riinu's scripting diary

If it ain't broke, you're outdated

R: Replacing NAs in all factors with ‘Missing’

With a simple combination of mutate_if and fct_explicit_na, you can replace all NAs in all factors with “Missing”:

If some of the words/symbols appear in white font, see the example here: Gist: factor_NA_levels.R

dplyr reference:

forcats reference:



Handling your .bib file (LaTex bibliography)

To create a .bib file that only includes the citations you used in the manuscript:

bibexport -o extracted_file.bib manuscript.aux

There are a few issues with this though. The command bibexport comes with the installation of TexLive, but my Windows computer (bless) does not cooperate (“bibexport is not recognised as an internal or external command…”) . So I can only use it on my Mac (luv ya).


Get data from ggplot()

ggplot includes built in and seamless functionality that summarises your data before plotting it. As shown in the example below, ggplot_build() can be used to access the summarised dataset.


fill         y count prop x PANEL group    ...
#D7301F 0.2147239    35    1 1     1     4 ...
#FC8D59 0.6871166    77    1 1     1     3 ...
#FDCC8A 0.9570552    44    1 1     1     2 ...
#FEF0D9 1.0000000     7    1 1     1     1 ...
#D7301F 0.1696429    38    1 2     1     8 ...
#FC8D59 0.6116071    99    1 2     1     7 ...

HealthyR – a new 2.5 day quick-start R course



R lingua: library vs package



Online syntax highlighter


The style I use: Dawn

R: ISO codes and country names


iso = maps::iso3166

> str(iso)
'data.frame':   269 obs. of  5 variables:
 $ a2         : chr  "AW" ...
 $ a3         : chr  "ABW" ...
 $ ISOname    : chr  "Aruba" ..
 $ mapname    : chr  "Aruba" ...
 $ sovereignty: chr  "Netherlands" ...

Adding a Cron job using the ed editor

These commands (after the first one) work in the ed editor. ed editor is used in the RStudio server shell.

sudo crontab -e                                     #opens crontab file in chosen editor

a                                                   #add to file
0,30 * * * * Rscript /home/user/folder/script.R     #command to add
.                                                   #finished editing
,p                                                  #print file content to check
w                                                   #save changes
Q                                                   #quit

In this example the script will run every 0 hours, 30 minutes, see Ubuntu: How do I set up a CRON job for other options.


Powered by

Up ↑