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 <- 1
1 + (2 - 3) / 4 * 5
3 %% 2
is 12 ^ 3
is
2 * 2 * 2
quarter1
not
1quarter
first_person
firstperson
, first.person
, or
FirstPerson
1
is the same as
1.0
1L
1234.56
instead of
$1,234.56
Backtick
is for field names in dplyrTRUE
or FALSE
T
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
,
ncol
summary
, str
df[rows, columns]
df$field_name
order
or
subset
my_list <- list(name1 = 'a', name2 = 1, name3 = 1:10)
my_list$name1
Great introduction to types! https://www.datacamp.com/tutorial/data-types-in-r
Yarr is a gentle introduction to using R. If you haven’t done any programming before, this could be a good way to get started. https://bookdown.org/ndphillips/YaRrr/jumpin.html
W3 Schools has a nice reference for R code. This is really good for trying to lookup a specific feature. https://www.w3schools.com/r/default.asp