[emaillocker]Below are the solutions to these exercises on loops.

#################### # # # Exercise 1 # # # #################### for (i in 1:7) { print(i^3) }

## [1] 1 ## [1] 8 ## [1] 27 ## [1] 64 ## [1] 125 ## [1] 216 ## [1] 343

#################### # # # Exercise 2 # # # #################### for (n in names(iris)) { print(paste0(n, " (", nchar(n), ")")) }

## [1] "Sepal.Length (12)" ## [1] "Sepal.Width (11)" ## [1] "Petal.Length (12)" ## [1] "Petal.Width (11)" ## [1] "Species (7)"

#################### # # # Exercise 3 # # # #################### set.seed(3) while (TRUE) { x <- rnorm(1) print(x) if (x > 1) { break } }

## [1] -0.9619334 ## [1] -0.2925257 ## [1] 0.2587882 ## [1] -1.152132 ## [1] 0.1957828 ## [1] 0.03012394 ## [1] 0.08541773 ## [1] 1.11661

#################### # # # Exercise 4 # # # #################### set.seed(3) while (TRUE) { x <- rnorm(1) if (x < 0) { next } print(x) if (x > 1) { break } }

## [1] 0.2587882 ## [1] 0.1957828 ## [1] 0.03012394 ## [1] 0.08541773 ## [1] 1.11661

#################### # # # Exercise 5 # # # #################### n <- 20 coin_outc <- vector(length = n, mode = "integer") for (i in 1:20) { coin_outc[i] <- sample(c(0L, 1L), 1) } coin_outc

## [1] 0 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0

#################### # # # Exercise 6 # # # #################### mat <- matrix(NA_integer_, nrow = 5, ncol = 5) for (i in 1:5) { for (j in 1:5) { mat[i, j] <- abs(i - j) } } mat

## [,1] [,2] [,3] [,4] [,5] ## [1,] 0 1 2 3 4 ## [2,] 1 0 1 2 3 ## [3,] 2 1 0 1 2 ## [4,] 3 2 1 0 1 ## [5,] 4 3 2 1 0

#################### # # # Exercise 7 # # # #################### target <- 1e8 product <- 1 n <- 0 while (product <= target) { n <- n + 1 product <- product*n } n

## [1] 12

#################### # # # Exercise 8 # # # #################### set.seed(22) price_start <- 100 price <- price_start target_diff <- 50 n <- 0 while (abs(price_start - price) < target_diff) { n <- n + 1 price <- price*(1 + rnorm(mean = 0, sd = 0.01, n = 1)) } n

## [1] 2164

#################### # # # Exercise 9 # # # #################### x <- 0L while (TRUE) { cat( "I am thinking of a number between 1 and 10.", "\nTake a guess and press enter twice!" ) x <- scan()[1] if (x == 5) { cat("Right!") break } cat("Wrong\n") }

#################### # # # Exercise 10 # # # #################### total <- 0 while (TRUE) { if (!total %in% 0:4) { total <- 0L } n <- sample(c(2:12), 2) cat("What is the product of ", n[1], " and ", n[2], "?\n", sep = "") x <- as.integer(readline()) if (x == prod(n)) { total <- total + 1L cat("Right!") if (total == 5) break cat(" You just need", 5 - total, "more answers.\n\n") } else { cat("Wrong\n") } }

[/emaillocker]

## Leave a Reply