Ex S1

Please calculate “factorial(10)” by using a “for” loop and a “while” loop, respectively

factor <- 1
for(i in 1:10){
        factor = factor*i
}
paste("this for loop can get",factor,sep = " ")
## [1] "this for loop can get 3628800"
i <- 1
factor <- 1
while (i <= 10) {
        factor = factor*i
        i = i+1
}
paste("this while loop can also get",factor,sep = " ")
## [1] "this while loop can also get 3628800"

Revisit Ex 12

x <- c(3600, 5000, 12000, NA, 1000, 2000, 600, 7500, 1800, 9000), please end the loop once you meet the missing value, and please tell me which observation is the missing value.

x <- c(3600, 5000, 12000, NA, 1000, 2000, 600, 7500, 1800, 9000)
i <- 1
done <- FALSE
while(!done){
        if(!is.na(x[i])){
                i <- i + 1
        }else{done <- TRUE}
}

cat(i)
## 4
cat(paste("the NA value is at the",i,"th number"),sep = " ")
## the NA value is at the 4 th number

Ex 15

Please plot the BMI curves for ID51-ID60, to the right of ID1-ID10. Please put a title as “Drug group” and make a legend.

read the data first

bmi <- read.csv("BMIrepeated.csv")
x <- seq(0,9,3)
y <- cbind(bmi$BMI0, bmi$BMI1, bmi$BMI2, bmi$BMI3)

plotting 1-10 & 51-60

par(mfrow = c(1,2))
plot(x,y[1,], type = "b", lwd = 1, col = 1, lty = 1, pch = 1,axes = F,
     ylim = c(15,50), xlab = "months", ylab = "BMI", main = "Placebo Group")
axis(1,at = x, labels = seq(0,9,3))
axis(2)

for (subj in 2:10){
        lines(x,y[subj,], lty = 1, lwd = 1,
              col = subj, type = "b", pch = subj)}

legend(x =7,y = 52, bty = "n",
       c("ID1","ID2","ID3","ID4","ID5","ID6","ID7","ID8","ID9","ID10"),
       lty = 1, col = (1:10), lwd = 1,pch = (1:10),cex = 0.5)

# 51-60
plot(x,y[51,], type = "b", lwd = 1, col = 1, lty = 1,pch = 1,axes = F,
     ylim = c(15,50), xlab = "months", ylab = "BMI", main = "Drug Group")
axis(1,at =x,labels = seq(0,9,3))
axis(2)
# for (subj in 52:60) {
#         lines(x,y[subj,], lty = 1, lwd = 1,
#               col = subj, type = "b", pch = subj)}
for (subj in 52:60) {
        lines(x,y[subj,], lty = 1, lwd = 1,
              col = (subj-50), type = "b", pch = (subj-50))}

legend(x =7,y = 52, bty = "n",
       c("ID51","ID52","ID53","ID54","ID55","ID56","ID57","ID58","ID59","ID60"),
       lty = 1, col = (1:10), lwd = 1,pch = (1:10),cex = 0.5)

Ex S2

Please add percentages to the 3D pie chart on page 4 of this handout

library(plotrix)
## Warning: package 'plotrix' was built under R version 4.3.2
subject <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pct <- round(subject/sum(subject)*100)
lbls <- paste(lbls,pct)
lbls <- paste0(lbls,"%")
pie3D(subject,labels=lbls,explode=0.1,main="Pie Chart of Countries ",
      col = c("lemonchiffon","lightpink","lightsalmon","palevioletred","lightpink4"))