<- 26 weight
Introduction to R and RStudio (reference card)
Variables
Store values using the assignment operator <-
(or =
):
To display the value use the name of the variable:
<- 26
weight weight
[1] 26
Functions
Run functions using name_of_function(arguments)
:
round(weight, 0)
[1] 26
Vectors
Store multiple values together in a vector using c()
:
<- c(9, 16, 3, 10)
count count
[1] 9 16 3 10
Many functions take a vector as an argument and return a single value:
mean(count)
[1] 9.5
Slicing vectors
Get a piece of a vector:
2:3] count[
[1] 16 3
Null values
Nulls are stored as NA
:
<- c(9, 16, NA, 10)
count_na count_na
[1] 9 16 NA 10
Ignore NA
in calculations on vectors with na.rm = TRUE
:
mean(count_na, na.rm = TRUE)
[1] 11.66667
Vector math
Doing math with vectors will do the calculation elementwise and return a vector of the same length as the original vectors.
<- c(9, 16, 3, 10)
count <- c(3, 5, 1.9, 2.7)
area <- count / area
density density
[1] 3.000000 3.200000 1.578947 3.703704
Filtering vectors (subsetting)
Select parts of a vector based on conditions using []
.
To check if two things are equal use ==
(not =
).
Other operators include <
, <=
, >
, >=
.
<- c("FL", "FL", "GA", "SC")
states <- c(9, 16, 3, 10)
count <- c(3, 5, 1.9, 2.7)
area
== 'FL'] area[states
[1] 3 5
> 2] count[area
[1] 9 16 10
> 2] count[count
[1] 9 16 3 10
Comments
Write information intended for people, not the computer using
#
: