# Exercise 1. x <- c(-4, 1, 0, 0, 5, -3, 2) y <- c(1, 1, -5, 4, 3, -2, 0) x[c(1, 2, 6)] y[1:4] x[x<0] x[-3] x[x<0 & y!=1] y[y<0 | x<=0] y[rep(1:2,2)] # Exercise 2. x <- 5 y <- 7 s1 <- (x+y) / 2 s1 s1 <- mean(c(x,y)) s1 s2 <- 4 * (x<7) + y * (x>=7) + 1 * (x>8) s2 s3 <- min(c(x,y)) s3 s4 <- (x+y)/2 * (x>=5) + y * (x<5) s4 # Exercise 3. A <- matrix(c(1,2,6,5,2,5,6,1,3), byrow=T, nrow=3) B <- matrix(c(1,1,1,2,1,3), byrow=T, nrow=3) C <- diag(diag(A)) 5*solve(A)+3*solve(A%*%t(A))-2*B%*%t(B)+diag(3)+diag(c(5,6,3)) # Exercise 4. #a chem<-c(93,71,77,78,77,81,88,74,67,78,77,67,63,83,73,70,78,95,88,75) phys<-c(42,67,59,70,59,50,50,51,45,64,49,49,48,51,56,47,53,56,49,71) math<-c(98,68,36,92,44,45,58,31,70,46,41,46,65,62,20,22,92,56,28,94) arch<-c(34,33,24,24,31,22,23,32,31,26,75,81,87,100,81,100,77,89,100,77) sex <- factor(c(rep("Male",6),rep("Female",4),rep("Male",2), rep("Female",4),rep("Male",4))) year<-c(1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2) grades <-data.frame(chem,phys,math,arch,sex,year) #b sgr <- split(grades, grades$sex) mycolmeans <-function(x, index) { colMeans(x[, index]) } lapply(sgr, mycolmeans, index=1:4) #c sapply(grades[,1:4],max) #d max(grades[,1:4]) #e #overall avgr <- apply(grades[,1:4],1,mean) cbind(sort(avgr),grades[order(avgr),]) # by year sgr2 <- split(grades,grades$year) myrowmeans <- function(x, index){ rowMeans(x[, index]) } avgr2 <- lapply(sgr2, myrowmeans, index=1:4) cbind(sort(avgr2[[1]]), sgr2[[1]][order(avgr2[[1]]),]) cbind(sort(avgr2[[2]]), sgr2[[2]][order(avgr2[[2]]),]) #f grades2 <- grades grades2[,1:4] <- sapply(grades[,1:4],scale) avgr.st <- apply(grades2[,1:4],1,mean) which.max(avgr.st) grades[which.max(avgr.st),] #g res1 <- sapply(grades[,1:4], function(x) x>=50) res2 <- apply(res1,1,function(x) all(x)) sum(res2)/length(res2) #e suc <- grades[res2,1:4] sapply(suc[,1:4],mean) sapply(suc[,1:4],var)