Basic data types + Variable assignment

#Numeric
y <- 2.0 #decimal
x <- 2 #integer to us, but a decimal to R
z <- 2L #integer
p <- as.integer(2) #built in function that allows us to turn numbers into integers

#String/character
a <- "hello"
b <- hello #doesn't work because no ""
class(a)

#Logical - True or False
c <- TRUE
p <- "TRUE" #character data type because of ""
h <- "2" #character data type because of ""

class(c)
class(p)
class(h)

#Factors or "categories" - need to convert vectors into categories
d <- c(1, 2, 3)
class(d)
d <- as.factor(d)
class(d)

u <- c("red", "green", "blue") #works with strings/characters too
class(u)
u <- as.factor(u)
class(u)

Introducing container types + dataframes

#Vectors - a container that holds same types of data 
a <- c(1, 2, 3)
c <- c(1, "hello", TRUE) #all values will be converted into characters
b <- c("a", "b", "c")
#Accessing vector items via indexing with []
a[3]
b[1]

#Lists - a container that hold different types of data
c <- c(1, "hello", TRUE)
l <- list(1, "hello", TRUE)
x <- list(1:5, "p", TRUE, 2.5)
#Access specific list items by index [[]] 
l[[3]]
x[[4]]
l[[2]]
#Access specific list items via name by $ 
l <- list(1, "hello", TRUE)
x <- list(a = 1, b = "hello", c = TRUE)
x$a

#Matrices - 2d array of same data type (think of it like a table)
x <- matrix(1:9, nrow = 3) # matrix(what you want in the table, specify how many rows in the table)
x
#Accessing elements in matrix, matrixname[row index, column index]
x[1, 3]
x[3, 2]
x[1, ]
x[, 3]

#Dataframes - similar to matrix but mixed data types, just think of your regular table of data
df <- data.frame(column1 = c(1, 2, 5, 6), column2 = c("a", "b", "c", "d"))
df <- data.frame(column1 = c(1, 2, 5, 6), column2 = c("a", "b", "c", "d"))
df
df[1, 2]
df$column2[1]

Functions - making your own custom functions

#Some build in functions that we've used so far
class()
matrix()
c()
list()
data.frame()
as.integer()

adder <- function(a, b) {
  print(a+b)
}

Loops and conditional flow

#For loops
#I want to print out the number 1:5
print(1)
print(2)
print(3)
print(4)
print(5)

#Using a for loop to streamline the process
for(i in c(1, 2, 3, 4, 5)) {
  print(i)
} #for everytime i is each element of c(1,2,3,4,5), do what is inside the curly brackets 

#Another for loop example
for(i in c(2, 4, 6)) {
  print(i + 1)
  print(class(i+1))
}

#While loops
x <- 10
while(x > 5) {
  print(paste("x =", x, ", and x is greater than 5"))
  x <- x - 1
} #while x is still greater than 5, keep doing what is inside the curly brackets


#If statements
x <- 12
y <- 20
if(x<y) {
  z<-20
  print("Y is bigger")
} else if(x==y) {
  print("They are equal!")
} else {
  z<-10
  print("X is bigger")
} #if x is less than y, do the first curly bracket, and if equal then do the second curly bracket, if none of those then do the last curly bracket