You are on page 1of 2

Base R Vectors Programming

Creating Vectors For Loop While Loop


Cheat Sheet c(2, 4, 6) 2 4 6
Join elements into
for (variable in sequence){ while (condition){
a vector

Do something Do something
Getting Help An integer
2:6 2 3 4 5 6
sequence } }

Accessing the help files seq(2, 3, by=0.5) 2.0 2.5 3.0


A complex Example Example
sequence
?mean for (i in 1:4){ while (i < 5){
Get help of a particular function. rep(1:2, times=3) 1 2 1 2 1 2 Repeat a vector
j <- i + 10 print(i)
help.search(weighted mean)
print(j) i <- i + 1
Search the help files for a word or phrase. rep(1:2, each=3) 1 1 1 2 2 2 Repeat elements
of a vector
help(package = dplyr) } }
Find help for a package. Vector Functions
More about an object If Statements Functions
sort(x) rev(x)
Return x sorted. Return x reversed. if (condition){ function_name <- function(var){
str(iris)
table(x) unique(x) Do something
Get a summary of an objects structure. Do something
See counts of values. See unique values. } else {
class(iris) Do something different return(new_variable)
Find the class an object belongs to. } }
Selecting Vector Elements
Example
Using Libraries Example
By Position if (i > 3){ square <- function(x){
install.packages(dplyr) x[4] The fourth element. print(Yes)
squared <- x*x
Download and install a package from CRAN. } else {
print(No) return(squared)
library(dplyr) x[-4] All but the fourth.
} }
Load the package into the session, making all
its functions available to use. x[2:4] Elements two to four.
Reading and Writing Data
dplyr::select All elements except
x[-(2:4)] Input Ouput Description
Use a particular function from a package. two to four.

Elements one and Read and write a delimited text


data(iris) df <- read.table(file.txt) write.table(df, file.txt)
x[c(1, 5)] file.
five.
Load a built-in dataset into the environment.
By Value Read and write a comma
Working Directory x[x == 10]
Elements which df <- read.csv(file.csv) write.csv(df, file.csv) separated value file. This is a
special case of read.table/
are equal to 10.
write.table.
getwd()
All elements less
Find the current working directory (where x[x < 0]
than zero. Read and write an R data file, a
inputs are found and outputs are sent). load(file.RData) save(df, file = file.Rdata)
file type special for R.
x[x %in% Elements in the set
setwd(C://file/path) c(1, 2, 5)] 1, 2, 5.
Change the current working directory.
Named Vectors Greater than
a == b Are equal a > b Greater than a >= b is.na(a) Is missing
or equal to
Conditions
Use projects in RStudio to set the working Element with Less than or
x[apple] a != b Not equal a < b Less than a <= b is.null(a) Is null
directory to the folder you are working in. name apple. equal to

RStudio is a trademark of RStudio, Inc. CC BY Mhairi McNeill mhairihmcneill@gmail.com Learn more at web page or vignette package version Updated: 3/15
Types Matrixes Strings Also see the stringr library.
m <- matrix(x, nrow = 3, ncol = 3) paste(x, y, sep = ' ')
Converting between common data types in R. Can always go Join multiple vectors together.
Create a matrix from x.
from a higher value in the table to a lower value.
paste(x, collapse = ' ') Join elements of a vector together.
m[2, ] - Select a row t(m)

w
ww Transpose
grep(pattern, x) Find regular expression matches in x.

ww
as.logical TRUE, FALSE, TRUE Boolean values (TRUE or FALSE).

w m[ , 1] - Select a column
m %*% n gsub(pattern, replace, x) Replace matches in x with a string.

Integers or floating point


w
ww Matrix Multiplication toupper(x) Convert to uppercase.

ww
as.numeric 1, 0, 1
numbers.

w m[2, 3] - Select an element


solve(m, n)
Find x in: m * x = n
tolower(x) Convert to lowercase.
as.character '1', '0', '1'
Character strings. Generally

w
ww
ww
preferred to factors. nchar(x) Number of characters in a string.

as.factor
'1', '0', '1',
levels: '1', '0'
Character strings with preset
levels. Needed for some
statistical models.
w Lists Factors
l <- list(x = 1:5, y = c('a', 'b')) factor(x) cut(x, breaks = 4)
Maths Functions A list is collection of elements which can be of dierent types. Turn a vector into a factor. Can
set the levels of the factor and
Turn a numeric vector into a
factor but cutting into
log(x) Natural log. sum(x) Sum. l[[2]] l[1] l$x l['y'] the order. sections.
New list with New list with
exp(x) Exponential. mean(x) Mean. Second element Element named
only the first only element
max(x) Largest element. median(x) Median.
of l.
element.
x.
named y. Statistics
min(x) Smallest element. quantile(x) Percentage
lm(x ~ y, data=df) prop.test
Also see the t.test(x, y)
quantiles.
dplyr library. Data Frames Linear model. Preform a t-test for Test for a
round(x, n) Round to n decimal rank(x) Rank of elements. dierence
dierence between
places. glm(x ~ y, data=df) between
df <- data.frame(x = 1:3, y = c('a', 'b', 'c')) means.
Generalised linear model. proportions.
signif(x, n) Round to n var(x) The variance. A special case of a list where all elements are the same length.
significant figures. pairwise.t.test
List subsetting summary aov
Preform a t-test for
cor(x, y) Correlation. sd(x) The standard x y Get more detailed information Analysis of
paired data.
deviation. out a model. variance.
df$x df[[2]]
1 a
Variable Assignment Distributions
2 b Understanding a data frame
> a <- 'apple' Random Density Cumulative
Quantile
> a See the full data Variates Function Distribution
3 c View(df)
[1] 'apple' frame. Normal rnorm dnorm pnorm qnorm
See the first 6
Matrix subsetting head(df) Poison rpois dpois ppois qpois
rows.
The Environment Binomial rbinom dbinom pbinom qbinom
df[ , 2]
ls() List all variables in the nrow(df) cbind - Bind columns. Uniform runif dunif punif qunif
environment. Number of rows.

rm(x) Remove x from the


environment. df[2, ]
ncol(df)
Number of
Plotting Also see the ggplot2 library.

columns.
rm(list = ls()) Remove all variables from the rbind - Bind rows. plot(x) plot(x, y) hist(x)
environment. Values of x in Values of x Histogram of
dim(df)
Number of order. against y. x.
You can use the environment panel in RStudio to
df[2, 2] columns and
browse variables in your environment. rows.
Dates See the lubridate library.

RStudio is a trademark of RStudio, Inc. CC BY Mhairi McNeill mhairihmcneill@gmail.com 844-448-1212 rstudio.com Learn more at web page or vignette package version Updated: 3/15

You might also like