## Basic calculations # Addition: `+` # Subtraction: `-` # Multiplication: `*` # Division: `/` # Exponentiation: `^` # Modulo: `%%` # An addition 2 + 5 # A subtraction 10 - 5 # A multiplication 2 * 6 # A division (6 + 2) / 2 # Exponentiation 10^2 # Modulo 11%%3 ## Variable assignment # Assign the value 50 to `x` x <- 50 # Print out the value of the variable `x` x # Assign the value 2 to `y` and sum `x + y` y <- 2 x + y ## Data type/classes # Numeric, integer, logic, character, factor, etc. # Numeric class class(x) is.numeric(x) is.integer(x) x_int <- as.integer(x) is.integer(x_int) ### String class # Stores all kinds of text data. my_name <- "Juan" my_name class(my_name) is.character(my_name) is.character(x) is.numeric(my_name) x + my_name ### Logical class # Stores boolean truth values, i.e. TRUE and FALSE. # Numeric values can be converted to logical (0 = false, all others = true). 3 > 2 2 > 3 3 == 3 4 == 3 4 >= 3 my_T <- 3 > 2 my_F <- 2 > 3 my_T my_F class(my_T) is.logical(my_F) as.logical(0) as.logical(1) #Example of logical operations: my_T | my_F my_T & my_F !my_T ### Factors # Not discussed here ## Basic data structures # Vectors, matrices, data frames. ### Vectors # One-Dimensional arrays. All elements must have the same type. # They are declared with `c(...)`. v <- c("Juan", 2, TRUE) v class(v) w <- c(1, 2, 3) w class(w) ### Matrix. # Two dimensional version of a vector. # Also requires all data to be of the same type. # Produce a matrix A <- matrix( c(2, 4, 3, 1, 5, 7), # the data elements nrow = 3, # number of rows ncol = 2, # number of columns byrow = FALSE) # fill matrix by rows A # Access elements of the matrix A[1,] # first row A[,1] # first column A[c(1,3),] # row 1 and 3 A[2,2] #element in second row, second column ### Data frame # Used to store data with columns of different data-types. students <- c("Juan","Johan","Joan","John","Giovanni") country <- c("Mexico","Sweden","Sweden","England","Italy") age <- c(20,21,24,19,30) is_exchange <- c(TRUE,FALSE,FALSE,TRUE,TRUE) my_class <- data.frame(Name = students, Country = country, Age = age, Exchange = is_exchange, stringsAsFactors = FALSE) my_class # Access data from a data frame. # It can be done in the same way as with matrices, e.g. with the `[r,c]` notation. # It can also be done using the `$` notation to access specific columns. my_class$Age my_class$Country my_class$Exchange