Richard Wen (rrwen.dev@gmail.com)
A quick introduction to R, which includes installation, basic examples, and references to learning resources.
Requirements
- R [Download]: a free programming language that is widely used for statistics and data analysis
- RStudio [Download]: a graphical interface and various tools to make writing R code easier
1.0 Quick Start
2.0 Basic Examples
- Help
- Comments and Output
- Math
- Variables
- Loops
- Vectors
- Dataframes
- Summaries and Plots
- Read and Write
- Packages and Libraries
- Script Editor: Run, edit, and save R code using script files (.R)
- Console: Execute and output code
- Variables/Objects: Inspect variables and objects in the global environment
- Help/Plots/Misc: Visualization, help documentation, package, and file interfaces
The following can be run in either the console or the script editor.
Get help documentation using ?
?read.table
?write.table
?vector
?data.frame
?summary
?plot
?lm
Commenting using #
and console output using print()
# This is a comment, it does not get executed
print("Some text") # It can be used on the same line as the actual code
Simple arithmetic operations:
- addition
+
- subtraction
-
- multiplication
*
- division
/
- exponent
^
1 + 1 # add
2 - 1 # sub
2 * 2 # multiply
10 / 2 # div
4^2 # exp
Variable assignment using <-
x <- 1
y <- x + 1 # y == 2
Basic for
loop
x <- 0
for (i in 1:5) { # Add 1 to x, 5 times
x <- x + 1
}
Create a vector using c()
height <- c(4.8, 4.5, 5.75)
eyeColor <- c("blue", "brown", "green")
eyeColor[1] # select the 1st eyeColor
height[c(1,3)] # select 1st and 3rd height
height + 0.1 # add 0.1 to all heights
Create a dataframe (table-like structure) using data.frame()
dataset <- data.frame(height=c(4.8, 4.5, 5.75),
eyeColor=c("blue", "brown", "green"))
dataset[1, ] # select 1st row
dataset[, 2] # select 2nd column
dataset$eyeColor # select 2nd column by name
Obtain a summary or plot using summary()
or plot()
summary(dataset) # mean, median, mode, stdev, etc
plot(dataset) # height vs eyeColor
Read/write table-formatted data using read.table
dataset <- read.table("file.txt")
write.table(dataset, "new_file.txt")
Package management using install.packages()
and remove.packages()
Load package libraries using library()
install.packages("ggplot2")
remove.packages("ggplot2")
library(utils)
- Base R Cheatsheet by Mhairi McNeill for more basic R code
- RStudio cheatsheets for quick R code references
- Online learning resources suggested by RStudio
- A short 12 page introduction to R by Paul Torfs and Claudia Brauer
- Google's R Style Guide for R coding practices
- Advanced R by Hadley Wickham