Base Vectors Programm
Creating For ing While
Cheat Vectors Loop Loop
R
Sheet
c(2, 4, 6) 2 4 6
Join elements
into a
vector
for (variable in sequence){
Do something
while (condition){
Do something
2:6 2 3 4 5 6 An
integer } }
sequenc
Getting e
Example Example
A
?mean Help seq(2, 3, by=0.5) 2.0 2.5 3.0
complex
sequenc
for (i in 1:4){ while (i < 5){
Get help of a particular function. e j <- i + 10 print(i)
Accessing the help
[Link](‘weighted mean’)
rep(1:2, times=3) 1 2 1 2 1 2 print(j) i <- i + 1
Searchfiles
the help files for a word or Repeat a vector
phrase. help(package = } }
rep(1:2, each=3) 1 1 1 2 2 2 Repeat
‘dplyr’) Vector Functions elements of
a vector
Find help for a package.
sort(x) rev(x) If Functio
More about an object Statement ns
Return x sorted. Return x if (condition){ function_name <- function(var){
table(x) reversed. s
Do something
str(iris) Do something
See counts of unique(x) } else {
Get a summary of an object’s Do something
values. See unique return(new_variable)
structure. different }
values.
Selecting Vector Elements
class(iris) }
Example Example
Find the class an object belongs
By Position
to. if (i > 3){ square <- function(x){
x[4] The fourth print(‘Yes’)
Using element. } else {
squared <- x*x
Packages
library(dplyr) x[-4] All but the
}
print(‘No’)
}
return(squared)
fourth.
Load the package into the session,
[Link](‘dplyr’)
making all and
its functions available to x[2:4] Elements two to
Download install a package
four.
Reading and Also see the readr
use.
from CRAN. package.
dplyr::select All elements Input Writing DataOuput Description
x[-(2:4)]
Use a particular function from a except two to
package. four. Read and write a delimited
data(iris) Elements one df <- [Link](‘[Link]’) [Link](df, ‘[Link]’)
x[c(1, 5)] text file.
Load a built-in dataset into the and five.
environment. By Value Read and write a
Working x[x == 10]
Elements df <- [Link](‘[Link]’) [Link](df, ‘[Link]’) comma separated value
file. This is a special
which are
Directory equal to 10.
case of [Link]/
[Link].
All elements
x[x < 0]
getwd() less than
zero. load(‘[Link]’) save(df, file = ’[Link]’) Read and write an R data
Find the current working directory x[x %in% Elements in the file, a file type special
(where inputs are found and c(1, 2, 5)] set 1, 2, 5. for R.
outputs are sent).
Named Vectors a == b Are equal a > b Greater a >= b Greater
[Link](a) Is missing
setwd(‘C://file/path’) Conditio than
than or
Use projects in RStudio to set the Element
equal to
Change the current working
working directory to the folder x[‘apple’] ns
a != b a < b a <= b Less than
with name Not equal Less than [Link](a) Is null
directory.
you are working in.
or equal
‘apple’. to
RStudio® is a trademark of RStudio, Inc. • CC BY Mhairi McNeill • Learn more at web page or vignette • package version •
mhairihmcneill@[Link] Updated: 3/15
Types Matrices Strings Also see the stringr
package.
m <- matrix(x, nrow = 3, ncol = 3) paste(x, y, sep = ' ')
Converting between common data types in R. Can Join multiple vectors together.
Create a matrix from x.
always go from a higher value in the table to
paste(x, collapse = ' ') Join elements of a vector
a lower value.
m[2, ] - Select a t(m)
grep(pattern, x) together. Find regular
[Link] TRUE, FALSE, TRUE Boolean values (TRUE or row Transpos
FALSE). e m %*% gsub(pattern, replace, x) expression matches in x.
m[ , 1] - Select a
Integers or floating n toupper(x) Replace matches in x with a
[Link] 1, 0, 1
point numbers. column
Matrix
tolower(x) string.
Character strings. m[2, 3] - Select an Multiplication
[Link] '1', '0', '1' element nchar(x)
Generally preferred solve(m, n) Convert to
to factors.
Find x in: m * uppercase. Convert
Lists
'1', '0', '1', Character strings with
[Link]
levels: '1', '0' preset levels. Needed for
some statistical models.
x=n Factors
to lowercase.
l <- list(x = 1:5, y = c('a', 'b')) factor(x) cut(x,
Number of breaks = 4)
Maths A list is a collection of elements which can be of
different types.
Turn a vector into a factor.
Can set the levels of the
characters
Turn a in
string.
a
numeric vector
into a factor by ‘cutting’
log(x) Functions
Natural log. sum(x) Sum. l[[2]] l[1] l$x l['y'] factor and the order. into sections.
New list New list
exp(x) Exponential. mean(x) Mean. Second Element
with only with only
max(x) Largest median(x) Median.
element
the first
named
element Statisti
of l. x.
min(x) element. quantile(x) Percentag
element. named y.
lm(y ~ x,
cs
data=df) [Link]
Also see the [Link](x, y)
Smallest
e
quantiles dplyr Data Linear model. Perform a t-test Test for a
round(x, n) Round to n rank(x) difference
element.
decimal places.
. package.
df <- [Link](x =
Frames
1:3, y = c('a', 'b', 'c'))
glm(y ~ x, data=df)
for difference
between between
Rank of Generalised linear model. proportion
signif(x, n) Round to n var(x) The A special case of a list where all elements are the same means.
elements.
significant variance. length. [Link] s.
List summary aov
figures. Perform a t-test for
cor(x, y) sd(x) The x y subsetting Get more detailed paired data. Analysis
Correlation. standard information out a model. of
deviation. df$x df[[2]] variance
1 a
Variable Assignment Distributi .
> a <- 'apple'
2 b Understanding a data Rando ons
Densit Cumulativ
frame Quantile
> a See the full m y e
3 c View(df)
Variate Functio Distributio
[1] 'apple' data frame.
s n n
See the
Matrix head(df) Normal rnorm dnorm pnorm qnorm
first 6
The Environment subsetting
rows. Poisson rpois dpois ppois qpois
df[ , 2]
ls() List all variables in nrow(df) cbind - Bind Binomial rbinom dbinom pbinom qbinom
the environment. Number of columns.
rows. Uniform runif dunif punif qunif
rm(x) Remove x from
the df[2, ]
ncol(df)
Number
Plotti Also see the ggplot2
package.
rm(list = ls())
environment.
Remove all variables
of
columns. rbind - Bind
ng
plot(x) plot(x, y) hist(x)
from the environment. rows. Values of x Values of x Histogram
dim(df)
Number of in order. against y. of x.
You can use the environment panel in columns
df[2, 2]
RStudio to browse variables in
your environment.
and rows.
Dat See the lubridate
package.
RStudio® is a trademark of RStudio, Inc. • CC BY Mhairi McNeill • mhairihmcneill@[Link] • 844- esLearn more at web page or vignette • package version •
448-1212 • [Link] Updated: 3/15