Skip to content

rrwen/r-reference

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

41 Commits
 
 
 
 
 
 
 
 

Repository files navigation

R Reference

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

Contents

1.0 Quick Start
2.0 Basic Examples

3.0 References

1.0 Quick Start

  1. Install R and RStudio
  2. Open RStudio and begin coding in R:
  • 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

2.0 Basic Examples

The following can be run in either the console or the script editor.

Help

Get help documentation using ?

?read.table
?write.table
?vector
?data.frame
?summary
?plot
?lm

Comments and Output

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

Math

Simple arithmetic operations:

  • addition +
  • subtraction -
  • multiplication *
  • division /
  • exponent ^
1 + 1  # add
2 - 1  # sub
2 * 2  # multiply
10 / 2  # div
4^2  # exp

Variables

Variable assignment using <-

x <- 1
y <- x + 1  # y == 2

Loops

Basic for loop

x <- 0
for (i in 1:5) {  # Add 1 to x, 5 times
  x <- x + 1
}

Vectors

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

Dataframes

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

Summaries and Plots

Obtain a summary or plot using summary() or plot()

summary(dataset)  # mean, median, mode, stdev, etc
plot(dataset)  # height vs eyeColor

Read and Write

Read/write table-formatted data using read.table

dataset <- read.table("file.txt")
write.table(dataset, "new_file.txt")

Packages and Libraries

Package management using install.packages() and remove.packages()
Load package libraries using library()

install.packages("ggplot2")
remove.packages("ggplot2")
library(utils)

3.0 References