Contents

Getting Help

Accessing the Help Files

Get help of a particular function,

?mean

Search the help files for a word or phrase,

help.Search('weighted mean')

Find help for a package,

help(package='dplyr')

More About An Object

Get a summary of an object's structure,

str(iris)

Find the class an object belongs to,

class(iris)

Using Packages

Download and install a package from CRAN,

install.packages('dplyr')

Load the package into the session, making all its functions available to use,

library(dplyr)

Use a particular function from a package,

dplyr::select

Load a built-in dataset into the environment,

data(iris)

Working Directory

Find the current working directory (where inputs are found and outputs are sent),

getwd()

Change the current working directory,

# for windows
setwd('C://Users/...')
# for macosx
setwd('/Users/...')
# for linux
setwd('/home/...')

Vectors

Creating Vectors

Join elements into a vector,

v <- c(2, 4, 6)

An integer sequence,

v <- 2:6

An complex sequence,

v <- seq(2, 3, by=0.5)

Repeat a vector,

v <- rep(1:2, times=3)

Repeat elements of a vector,

v <- rep(1:2, each=3)

Vector Functions

Return x sorted,

sort(x)

Return x reversed,

rev(x)

See counts of values,

table(x)

See unique values,

unique(x)

Selecting Vector Elements

By Position

the fourth element,

x[4]

All but the forth,

x[-4]

Elements two to four,

x[2:4]

All elements except two to four,

x[-(2:4)]

Elements one and five,

x[c(1, 5)]

By Value

Elements which are equal to 10,

x[x == 10]

All elements less than zero,

x[x < 0]

Elements in the set 1, 2, 5,

x[x %in% c(1, 2, 5)]

Named Vectors

Elements with name 'apple',

x['apple']

Programming

For Loop

# for (variable in sequence) {
#   Do something
# }
for (j in 1:4) {
    j <- i + 10
    print(j)
}

While Loop

# while (condition) {
#   Do something
# }
i <- 0
while (i < 5) {
    print(i)
    i <- i + 1
}

If Statements

# if (condition) {
#   Do something
# } else {
#   Do something different
# }
i <- 3
if (i > 3) {
    print('Yes')
} else {
    print('No')
}

Functions

# function_name <- function(var) {
#   Do something
#   return(new_variable)
# }
square <- function(x) {
    squared <- x*x
    return(squared)
}

Reading and Writing Data

Read and write a delimited text file, - df <- read.table('file.txt') - write.table(df, 'file.txt')

Read and write a comma separated value file, - df <- read.csv('file.csv') - write.csv(df, 'file.csv')

Read and write an R data file, a file type special for R, - load('file.RData') - save(df, file='file.RData')

Matrices

m <- matrix(x, nrow=3, ncol=3)

Select a row,

m[2, ]

Select a column,

m[ , 1]

Select an element,

m[2, 3]

Transpose,

t(m)

Matrix multiplication,

m %*% n

Find x in: m*x=n,

solve(m, n)

Lists

A list is a collection of elements which can be of different types,s

l <- list(x=1:5, y=c('a', 'b'))

Second element of l,

l[[2]]

New list with only the first element,

l[1]

Element named x,

l$x

New list with only element named y,

l['y']

Data Frames

A special case of a list where all elements are the same length,

df <- data.frame(x=1:3, y=c('a', 'b', 'c'))
x y
1 a
2 b
3 c

List subsetting,

df$x
df[[2]]

See the full data frame,

View(df)

See the first 6 rows,

head(df)

Matrix subsetting,

df[ , 2]
df[2, ]
df[2, 2]

Number of rows,

nrow(df)

Number of columns,

ncol(df)

Number of columns and rows,

dim(df)

Bind columns,

cbind

Bind rows,

Strings

Join multiple vectors together,

paste(x, y, sep=' ')

Join elements of a vector together,

paste(x, collapse=' ')

Find regular expressoin matches in x,

grep(pattern, x)

Replace matches in x with a string,

gsub(pattern, replace, x)

Convert to uppercase,

toupper(x)

Convert to lowercase,

tolower(x)

Number of characters in a string,

nchar(x)

Factors

Turn a vector into a factor. Can set the levels of the factor and the order,

factor(x)

Turn a numeric vector into a factor by 'cutting' into sections,

cut(x, breaks=4)

Statistics

Linear model,

lm(y~x, data=df)

Generalized linear model,

glm(y~x, data=df)

Perform a t-test for difference between means,

t.test(x, y)

Perform a t-test for paired data,

pairwise.t.test

Test fir a difference between proportions,

prop.test

Analysis of variance,

aov

Distributions

Random Variates Density Function Cumulative Distribution Quantile
Normal rnorm dnorm pnorm qnorm
Poisson rpois dpois ppois qpois
Binomial rbinom dbinom pbinom qbinom
Uniform runif dunif punif qunif