2 minute read

This short tutorial helps you quickly start coding in the R language. It introduces you the environment, packages, reporting and naming and syntax styles.

The R Environment

  • If you bring a laptop to class, you can simply make installations in your laptop.

  • Otherwise, you may use lab computers but everytime you log in to a different computer, you have to reinstall all the required external packages. To avoid this issue, you can install external packages in a thumb drive and add it to the library path in R.

.libPaths() #print current path
## [1] "C:/Program Files/R/R-3.5.3/library"
new <- paste(.libPaths(), "pathToYourlibraryDir", sep=",")
.libPaths(new)
  • The IUanyware site will be the last option and you will for sure notice a long time lag.

The R language

Ch.1 Install R

RStudio

Ch.1 Install RStudio

R Packages

Ch.3

tidyverse:

  1. tibble
  2. readr(Ch.6)
  3. dplyr(Ch.12)
  4. ggplot2(Ch.7)
  5. tidyr
  6. purrr(Ch.13)

rmarkdown(Ch.28)

RStudio Projects (p19)

Project with Version Control (p19)

Reporting Tool: R Markdown

Ch.28

Terminal Commands

  • pwd
  • cd path/to/destination
  • ls -all
  • mkdir newdirectory
  • rm -rf directory
  • cp -rf source destination
  • vim

Run R script from CLI or Terminal pane in RStudio

  • Run R script

    Rscript script.R
  • Run R script and write output to a file

    Rscript script.R > output.txt
  • Render Rmd to HTML

    R -e "rmarkdown::render('script.Rmd',output_format='html_document',output_file='output.html')"

Style Guide

File name

An R script ends with .r or .R. An rmarkdown file ends with .rmd or .Rmd. Use a dash (-) to separate words. NO SPACE character within a name!

Object names

R treats everything as an object no matter it is a variable or a function. Object names should be lowercase. Use an underscore (_) or a dot (.) to separate words within a name. Generally, variable names should be nouns and function names should be verbs. Make names which are concise and meaningful.

raw_data
raw.data

Curly braces

An opening curly brace better never go on its own line and should always be followed by a new line. A closing curly brace should always go on its own line, unless it’s followed by else.

x <- 9 
tag <- TRUE
if (x > 0 && tag == TRUE) {
  print("X is positive.")
} else {
  print("X is unknown.")
}
sum <- 0
for (i in seq(1:10)) {
  sum <- sum + i
}
print(sum)

Comment lines

Use # sign and a single space to begin a comment line.

# Load data
comments powered by Disqus