### A sample session # set working directory setwd("~/Documents/Projects/200B/lab1/") # R works just like a calculator A "#" # signifies a comment and will be ignored by R # Basic math 3 + 5 3 * 10 4 ^ 10 exp(2) sin(1) ?exp # Vectors # use "c" to define a vector c(1,2,3,4) # "<-" assigns a value to a variable x <- c(1,2,3,4) # transpose t(x) length(x) sum(x) # element wise mulitplication x * t(x) # vector multiplication x %*% t(x) # some sequences 1:10 seq(0, 10, 0.5) seq(to = 0, from = 10, by = -0.5) # looking for a function ?product # doesn't exist help.search("product") # find prod ?prod prod(x) # list objects in workspace ls() #character name <- c("charlotte", "wickham") class(name) # convert character to numbers numbers <- c("1","2","3") numbers + 4 as.numeric(numbers) as.numeric(numbers) + 4 # Matrices # fills matrix by columns using vector z <- matrix(c(1,2,3,4,5,6,7,8), nrow = 2) matrix(c(1,2,3,4,5,6,7,8,9), nrow = 2) # examples of recycling matrix(c(1,2,3,4,5,6,7,8,9), nrow = 2, ncol = 6) matrix(3, nrow = 4, ncol = 4) # Subsetting matrices # 1st column z[,1] # 1st row z[1,] # item in 1st row and 1st column z[1,1] # column 1 and 2 z[,c(1,2)] # Dataframes x <- 1:10 y <- rep(c("a","b"),5) z <- x > 5 class(z) # logical class - T/F # vectors must be the same length # but can be different types obs <- data.frame(x, y, z) names(obs) # Subsetting a dataframe # a column obs[,2] # a row obs[3,] #column called x obs$x # columns x and y obs[,c("x","y")]