This file is an overview of the syntax in R. It provides a basic introduction to the major features.
It aligns with the Datacamp Introduction to R course.
R is case sensitive! So, var3 isn’t the same as
VAR3
#1 == 1 (not 1 = 1)variable_name <- 11 + (2 - 3) / 4 * 53 %% 2 is 12 ^ 3 is
2 * 2 * 2quarter1 not
1quarterfirst_person
firstperson, first.person, or
FirstPerson1 is the same as
1.01L1234.56 instead of
$1,234.56Backtick is for field names in dplyrTRUE or FALSET or F are also ok<, <=, >,
>=, ==, and != (not
equal)&| (vertical pipe)c(1, 2,3) or c("a", "b")vec[1] for first itemvec[length(vec)] for last itemvec[c(1, 3)] returns the 1st and 3rdvec[1:3] returns the 1st through the 3rdvec[c(T, F, T)] returns the 1st and 3rdname(vector) get/set names for each value
names(vec) <- c("A", "B", "C") to setvec[c("A")] or vec["A"] to access named
valuesvec > 10 to get c(T, F, T)vec[vec > 10]c(c(1), c(2)) turns
into c(1, 2)class(vec) to get data type of itemsclass(x) returns the class of a variablesummary(x) gives a quick summary of a numerical
vectormatrix(1:9, byrow = TRUE, nrow = 3)rownames(mat) and colname(mat) are used to
get/set namescbind and rbind combines vectors/matrixes
together by column or rowcolSums and rowSums sums up valuesmy_matrix[, 1] gets first columnmy_matrix[1, ] gets first rowmy_matrix[1, 1] gets first cellfactor(c('m', 'f', 'm', 'm', 'f'), c('m', 'f') )
ordered can be used to indicate that they have < and
> levelsrownames,
colnames, names, nrow,
ncolsummary, strdf[rows, columns]df$field_nameorder or
subsetmy_list <- list(name1 = 'a', name2 = 1, name3 = 1:10)my_list$name1Great introduction to types! https://www.datacamp.com/tutorial/data-types-in-r