Variable Assignment
a <- 'bonjour'
:
string
a <- 6
:
integer
Loop
For loop :
for (variable in sequence){ Do something }
While loop :
while (condition){ Do something }
Condition
if (condition){ Do something } else { Do something different }
a == b
: Are equal
a > b
: Greater than
a >= b
: Greater than or equal to
is.na(a)
: Is missing
a != b
: Not equal
a < b
: Less than
a <= b
: Less than or equal to
is.null(a)
: Is null
Functions
function_name <- function (var){ Do something return (new_variable) }
Maths Functions
log(x)
: Natural log /
sum(x)
: Sum
exp(x)
: Exponential /
mean(x)
: Mean
max(x)
: Largest element /
median(x)
: Median
min(x)
: Smallest element /
quantile(x)
: Percentage quantiles
round(x, n)
: Round to n decimal places
rank(x)
: Rank of elements
signif(x, n)
: Round to n significant figures
var(x)
: The variance /
cor(x, y)
: Correlation
sd(x)
: The standard deviation
Lists
l <- list(x = 1:5, y = c('a', 'b'))
: A list is collection of elements which can be of different types.
l[[2]]
: second element of l
l[1]
: new list with only the first element
l$x
: element named x
l['y']
: new list with only element named y
String
paste(x, y, sep = ' ')
: Join multiple vectors together.
paste(x, collapse = ' ')
: Join elements of a vector together.
grep(pattern, x)
: Find regular expression matches in x.
gsub(pattern, replace, x)
: Replace matches in x with a string.
toupper(x)
: Convert to uppercase.
tolower(x)
: Convert to lowercase.
nchar(x)
: Number of characters in a string.
Matrixes
m <- matrix(x, nrow = 3, ncol = 3)
: Create a matrix from x.
df[ , 2]
: Select a column .
df[2, ]
: Select a row.
df[2, 2]
: Select an element.
Data Frames
df <- data.frame(x = 1:3, y = c('a', 'b', 'c'))
: A special case of a list where all elements are the same length.
View(df)
: See the full data frame.
head(df)
:See the first 6 rows.
nrow(df)
: Number of rows.
ncol(df)
: Number of columns.
dim(df)
: Number of columns and rows.
As the same sub settings as matrixes and lists
Ploting
plot(x)
: plot values of x in order
plot(x, y)
: plot values of x against y
Reading and writing data
df <- read.table('file.txt')
/
df <- read.csv('file.csv')
/ Read a file text or a csv
write.table(df, ‘file.txt’)
/
write.csv(df, ‘file.csv’)
/ Write a file text or a csv
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by Todin