###Lesson 1 code### #Chunk 1# q() # Quits R (important if you use R without a GUI) ?command_name # Calls up the manual for a command (try ?q()) getwd() # Shows the working directory setwd("directory_name") # Sets the working directory #Chunk 2# ###Write and run this chunk of code directly in the console 2 2 + 2 a a <- 3 a a + 2 #Chunk 3# ###Write this chunk of code in an R script ###This is a comment### 2 #I can write comments wherever I want 2 + 2 #Sum of two numbers b b <- 5 # Assigning a value to an object b #Chunk 4# x <- 1 y <- 2 z <- 10 Peter <- x + y Bernard <- y - x Rabbit <- z * Peter #Chunk 5# typeof(x) #Chunk 6# word <- "hello" word2 <- "A?7Fd" mv <- NA Bool <- TRUE #Chunk 7# mode(x) mode(sin) mode(word) mode(Peter) #Chunk 8# v1 <- c(1,2,3,4) #Chunk 9# v2 <- c("a", 1, 2, 3) mode(v2) str(v2) #Chunk 10# d <- c(1, 2, 3, TRUE) e <- c("a", 2, 3, TRUE) #Chunk 11# v3 <- c(v1, v1, v1) v3 #Chunk 12# rep(4, 6) # The first argument gives the object to repeat, the second argument the number of repetitions seq(2, 4, 0.5) # Consists of values with distance 0.5 from 2 to 4 (including 2 and 4) 1:7 # A vector consisting of 1,...,7 seq(along = v2) # Vector (1,...,length(v2)) #Chunk 13# length(v2) class(v2) mode(v2) summary(v2) str(v2) mean(v2) var(v2) #Chunk 14# v1 <- 1:5 mode(v1) v1 + 5 #Chunk 15# v1[1] # The first entry of the vector v1[1] + 5 # The first entry of the vector increased by 5 v1[c(1, 2)] # The first two entries of the vector v1[-c(1, 2)] # All entries of the vector apart from the first two v1[v1<3] # All entries smaller than 3 #Chunk 16# logicv1 <- (v1>1) & (v1<4) v1[logicv1] #Chunk 17# v4 <- -7:3 # Defines v4 as the vector (−7, −6, ..., 1, 2, 3). Note the blank! which(v4>0) # Gives the positions of all entries of v4 bigger than 0 #Chunk 18# v1[1] <- 100 v1[1] v1 #Chunk 19# matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE) # Ordered by rows matrix2 <- matrix(c(1, 2, 3, 4), nrow = 2,byrow = FALSE) # Ordered by columns D <- diag(2) matrix3 <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 4, byrow = TRUE) #Chunk 20# matrix1[1,2] # Accesses the entry in the 1st row, 2nd column matrix1[ ,1] # Accesses the first column matrix1[1, ] # Accesses the first row #Chunk 21# colnames(matrix1) <- c("A","B") # Assign names to the columns of matrix1 rownames(matrix1) <- c("C", "D") # Assign names to the rows of matrix1 matrix1 matrix1["C","D"] matrix1[,"B"] #Chunk 22# v3 <- c(1, 1) # Defines a 2-dimensional vector t(matrix1) # Transposes matrix1 (switches rows with columns) matrix1 %∗% matrix2 # Multiplies matrix1 with matrix 2 matrix1 %∗% v3 # Multiplies matrix with vector solve(matrix1) # Inverts the matrix solve(matrix1, v3) # Solves the system of linear equation matrix1*x=v3 cbind(matrix1, v3) # Adds v3 as a new column (works also adding matrices) rbind(matrix1, v3) # Adds v3 as a new row (works also adding matrices)