## ----------------------------------------------------------------------------- for (i in 1:3) { print('hi') } ## ----------------------------------------------------------------------------- j <- 0 for (i in 1:3) { print(i) j <- j + i } j ## ----------------------------------------------------------------------------- for (i in 1:3) { txt <- paste('the square of', i, 'is', i * i) print(txt) } ## ----------------------------------------------------------------------------- s <- 0 a <- 1:6 b <- 6:1 # initialization of output variables res <- vector(length=length(a)) # i goes from 1 to 6 (the length of b) for (i in 1:length(b)) { s <- s + a[i] res[i] <- a[i] * b[i] } s res ## ----------------------------------------------------------------------------- for (i in 1:10) { if (i %in% c(1,3,5,7)) { next } if (i > 8) { break } print(i) } ## ----------------------------------------------------------------------------- i <- 0 while (i < 4) { print(paste(i, 'and counting ...')) i <- i + 1 } ## ----------------------------------------------------------------------------- set.seed(1) i <- 0 while(i < 0.5) { i <- runif(1) print(i) } ## ----------------------------------------------------------------------------- set.seed(1) while(TRUE) { i <- runif(1) print(i) if (i > 0.5) { break } } ## ----------------------------------------------------------------------------- x <- 5 y <- 10 ## ----------------------------------------------------------------------------- if (x == 5) { y <- 15 } y ## ----------------------------------------------------------------------------- if (x > 20) { y <- y + 2 } else if (x > 5 & x < 10) { y <- y - 1 } else { y <- x } y ## ----------------------------------------------------------------------------- b <- TRUE ## ----------------------------------------------------------------------------- if (b == TRUE) { print('hello') } ## ----------------------------------------------------------------------------- if (b) { print('hello') } ## ----------------------------------------------------------------------------- a <- 1:5 f <- vector(length=length(a)) for (i in 1:length(a)) { if (a[i] > 2) { f[i] <- a[i] / 2 } else { f[i] <- a[i] * 2 } } f