Getting re-acquainted with R

Posted: December 16, 2018 Category: backendTagged: RRStudio

Mostly a dumping ground for snippets wrt moving around in the environment and getting comfy. Probably a bit terse if you’ve not used RStudio before, but super handy if you’re jogging your memory, like me!

Handling the environment

CommandEffect
Ctrl + Enterexecute the currently selected code
Ctrl + Lclear console
ls()list all objs defined in current wrkspace. Handy!!
library(pkg)load a library named ‘pkg’. Note lack of quotes.
install.packages("pkg")install package named ‘pkg’.
devtools::install_github("u/p")install R lib from github project named ‘p’ from github user ‘u’. Of course, this requires that the ‘devtools’ package be already installed.
rm(x)remove object X from environment
rm(list=ls())remove all objects from the environment
rm(list = ls(all.names = TRUE))nuke everything incl all hidden objs
help(package = "pkg")See documentation for a library named ‘pkg’
?foosee the help file for a command named ‘foo’
args(foo)Just see what arguments a func named ‘foo’ takes. Useful!!
gc()garbage collect unused memory
CTRL + SHIFT + 10restart the whole damn R session :o)

Printing for debugging purposes

The following are equivalent; they both print out a variable named ‘x’:

  • print(x)
  • x

There are also:

  • head(x, n)
  • tail(x, n)

These print the first or last n entries of data held in a variable x.

There is also str(x), which shows you the structure of the object (named ‘x’, for example). This is SUPER handy and is easily the most useful function when you are wading about knee-deep in complex data structures.

There’s also class(x) for the type of object. The function class prints the vector of names of classes an object inherits from. It can also be set, but we won’t get into that here.


Managing environment configs

So this link is a beautiful thing. It describes how to set up config files for your R project! Relies on config.yml files that can be set up for different environments and gives you a singular file to .gitignore. Quoting:

You can specify which configuration is currently active by setting the R_CONFIG_ACTIVE environment variable. The R_CONFIG_ACTIVE variable is typically set within a site-wide Renviron or Rprofile (see R Startup for details on these files).

Simply brill, if you ask me.


Loading R files

Besides opening and running a file manually, you can ‘source’an R file from any location and execute it inline:

# note: check getwd() first... cos this path is relative
source("the/path/to/theFile.R")

# how to set the working directory to that of the currently running file
setwd(getSrcDirectory()[1])

Hope this helps other people also tinkering with R. I plan to tinker with Python too… but I’m not super interested in python proper, so I might go straight to Jupyter notebooks and work my way down from there…