#Q1
for(i in 0:10) {
if(i%%2!=0) cat(i)
}
#13579
#the odd numbers between 0 to 10
#Q2
notfound<-TRUE
i<-0
while(notfound) {
if(i%%2!=0) {
cat(i)
notfound<-FALSE
}
}
#Q3
#Which two of the following are the differences between the while and the repeat loops?
#
#Q4
#The repeat loop requires the break command to be exited manually
#The repeat loop body will be run at least once
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
#What is the command to find the mean of each list components?
lapply(x, mean)
#Q5
#What is the difference between lapply() and sapply()?
The lapply() outputs a list, whereas the sapply() outputs a vector or a matrix.
#L1
k<-1000
r<-100
set.seed(5556)
x<-as.data.frame(matrix(rnorm(r*k),nrow=r))
#L2
my.summary<-matrix(nrow=4,ncol=k)
for(i in 1:k){
my.summary[1,i] <-min(x[,i])
my.summary[2,i] <-median(x[,i])
my.summary[3,i] <-mean(x[,i])
my.summary[4,i] <-max(x[,i])
}
#L3
my.function<-function(x){
return(c(min(x),median(x),mean(x),max(x)))
}
#L4
#How would you use sapply() and my.function() to recalculate the result?
sapply(x,my.function)
#L5
#Calculate the runtime factor using the for loop and compare it to using sapply().
#Which operation took more time?
#The for loop
#If you increase the data (k and r), let say by 10 folds (either increase k or r by 10 times),
#and recalculate the runtime factor using the for loop and compare it to using sapply(), which operation took more time now?
#The for loop
#If you decrease the data (k and r), let say by 10 folds (either decrease k or r by 10 times), and recalculate the runtime factor using the for loop and compare it to using sapply(), which operation took more time now?
#The for loop