#Example 1 f1 <- function(x, y) { x+y } f1( 3, 4) #Example 2 f.bad <- function(x, y) { z1 <- 2*x + y z2 <- x + 2*y z3 <- 2*x + 2*y z4 <- x/y } f.bad(1, 2) f.good <- function(x, y) { z1 <- 2*x + y z2 <- x + 2*y z3 <- 2*x + 2*y z4 <- x/y return( z1, z2, z3, z4) } f.good(1, 2) #Example 3 f2 <- function(x, y) { z1 <- x + y z2 <- x + 2*y list(z1, z2) } f2(2, 5) f2(2, 5)[[1]] f2(2, 5)[[2]] f2(2, 5)$z1 #Example 4 f3 <- function(x, y) { z1 <- x + y z2 <- x + 2*y list(result1=z1, result2=z2) } f3(2, 5) f3(2, 5)$result1 f3(2, 5)$result2 #Example 5 y <- f3( 1, 4) names(y) y$result2 y[[2]] #Example 6 v1 <- seq(1, 6, 1) v1 v2 <- seq(2, 12, 2) v2 f3(v1, v2) mat1 <- matrix( c(1, 2, 3, 4, 5, 6), ncol=2) mat1 mat2 <- matrix( c(2, 4, 6, 8, 10, 12), ncol=2) mat2 f3(mat1, mat2) #Example 7 f4 <- function(x=3, y=2) { z1 <- x + y z2 <- x + 2*y list(result1=z1, result2=z2) } f4() #using the default value for the y argument f4(1, )$result1 f4(x=1)$result1 #using the default value for the x argument f4( , 1)$result1 f4(y=1)$result1 #switching the order of the arguments f4(y=1, x= 2)$result2 #Example 8 for(i in 2:4) { print(i) } #Example 9: for(i in c(1, 3, 6, 9)) { z <- i + 1 } z #using the print statement to see result at each iteration for(i in 3:5) { z <- i + 1 print(z) } #The list does not have to contain numbers cars <- c("Toyota", "Ford", "Chevy") for(j in cars) { print(j) } #Example 10: f5 <- function(x) { for(i in 1:x) { y <- i*2 print(y) } return(y*2) } f5(3) #Example 11 names1 <- c("Dave", "John", "Ann", "Roger", "Bill") f.names <- function(x) { for(name in x){ if(name=="Roger") break print(name) } } f.names(names1) #Example 12 i <- 2 while(i <= 4) { i <- i+1 print(i) } #Example 13 f6 <- function(x) { i <- 0 while(i < x) { i <- i+1 y <- i*2 print(y) } return(y*2) } f6(3) #Example 14 names1 <- c("Dave", "John", "Ann", "Roger", "Bill") f.names.while <- function(x) { i <- 1 while( x[i] != "Roger"){ print(x[i]) i <- i+1 } } f.names.while(names1) #Example 15 i <- 2 repeat { print(i) i <- i+1 if(i > 4) break } #Example 16 names1 <- c("Dave", "John", "Ann", "Roger", "Bill") f.names.repeat <- function(x) { i <- 1 repeat { print(x[i]) i <- i+1 if(x[i] == "Roger") break } } f.names.repeat(names1) #Example 17 random.sample1 <- function(epsilon) { i <- 0 repeat { i = i+1 mean.test <- abs( mean( rnorm(100) ) ) if (mean.test < epsilon ) break } list(mean=mean.test, number.iterations=i) } random.sample1(0.0001) #Example 18 x <- seq(1:5) ifelse(x < 3, "T", "F") #Example 19 norm2 <- rnorm(10, mean=2) norm2 log.normal <- ifelse(norm2<0, 0 , log(norm2) ) log.normal #Example 20 f1 <- function(x, ...) { y <- x+2 return(y) #other commands } f2 <- function( ... , x) { y <- x+2 return(y) #other commands } f1(3) f1(x=3) #f2(3) f2(x=3) #Example 21: x <- rnorm(100) y <- x + rnorm(100) windows(5,5) plot(x, y) windows(5,5) my.plot <- function(..., pch.new=15) { plot(..., pch=pch.new) } my.plot(x, y)