# for loops x <- c(3,4,8,5,1,4,9,4) sum(x) n <- length(x) val <- 0 for(i in 1:n){ # val gets added to in each step of the loop val <- val + x[i] } val sum(x) # another way: val <- 0 # don't need curly braces if there is only one line for(xvalue in x) val <- val + xvalue val # we can put a for loop inside a function :) my_sum <- function(x){ n <- length(x) val <- 0 for(i in 1:n){ # val gets added to in each step of the loop val <- val + x[i] } return(val) } my_sum(x) # counting characters in a string with a for loop ch <- "stRawberry" n <- nchar(ch) # get number of characters nr <- 0 # initialize the count at 0 for(i in 1:n){ # if(substr(ch,i,i) == "r"){ # # nr <- nr + 1 # # } nr <- nr + any(substr(ch,i,i) == c("r","R")) } nr # N <- 100 val <- 0 for(i in 1:N){ val <- val + (-1)^(i+1) / (2*i - 1) } val pi/4 # what if I want to keep track of the approximation as I go along?? N <- 100 val <- numeric(N) # make an empty vector (or a vector of 0s) val[1] <- 1 for(i in 2:N){ val[i] <- val[i-1] + (-1)^(i+1)/(2*i-1) } plot(val,type = "l") abline(h=pi/4,lty=3) val pi/4 # double for loop! x my_sort <- function(x){ n <- length(x) for(i in 1:(n-1)) for(j in (i+1):n){ if(x[i] > x[j]){ tmp <- x[j] x[j] <- x[i] x[i] <- tmp } } return(x) } x <- c(3,7,89,4,6,1,3,7,8,0) my_sort(x) sort(x) # super cool 3d plot myfun <- function(x,y) x*sin(x)*(1-y^2) gs <- 50 # grid size x <- seq(0,pi,length=gs) y <- seq(-1,1,length=gs) fxy <- matrix(0,gs,gs) # make an empty matrix for(i in 1:gs){ for(j in 1:gs){ fxy[i,j] <- myfun(x[i],y[j]) } } # use the persp() par(mar=c(1,1,1,1)) persp(x = x, y = y, z = fxy, box = F, theta = 30, phi = 30) # in this situation, we can use the # function outer() to avoid the double for loop # use the outer() function to evalute myfun() at # every combination of x and y and return a matrix fxy2 <- outer(x,y,FUN = myfun) persp(x,y,fxy2)