######################################################
######################################################
######################################################
# An R script that gives an overview of basic R commands
# in this file we will show how to do if/then statements
# and for and while loops
# For basic information on R variables, vectors, and matrices,
# see http://www.sherrytowers.com/basics.R
#
# Author: Sherry Towers
# admin@sherrytowers.com
# Created: Dec 1st, 2012
#
# Copyright Sherry Towers, 2012
#
# This script is not guaranteed to be free of bugs and/or errors.
#
# This script can be freely used and shared as long as the author and
# copyright information in this header remain intact.
######################################################
rm(list = ls(all = TRUE)) # resets R to fresh
######################################################
# let's create a vector, then loop over it and
# print some things that pass an if/then/else statement
######################################################
nsamp = 100
x = rnorm(nsamp) # randomly sample some numbers from the Normal distribution
n = length(x)
n # should be the same as nsamp
######################################################
# this is a for loop with index i that goes
# between 1 to n (the length of x).
# This kind of for loop is useful
# when you actually need to reference
# the vector index info within the loop
# For each step in the loop, R executes the commands
# within the curly braces that bracket the loop.
# Similarly, if the argument to an if statement is
# true, then R proceeds to execute the code within the curly
# brackets just after the if statement.
######################################################
count = 0
for (i in 1:n){ # the for loop index is i, and it goes between 1 to n
if (x[i]>3.0){ # if the boolean statement within the round brackets is true, the code block bracketed by the curly braces is executed
cat("The ",i,"th element of x is greater than +3: ",x[i],"\n",sep="")
}else if (x[i]<(-3.0)){
cat("The ",i,"th element of x is less than -3: ",x[i],"\n",sep="")
}else{ # if all the booleans above are false, the code within these curly braces is executed
cat("The ",i,"th element of x is between -3 to +3: ",x[i],"\n",sep="")
} # end check of value of x
if (abs(x[i])>3) cat("This is an example of the result of a one line if/then statement\n")
if (max(x[i])>3){
cat("This is an example of the result of just a plain if/then statement (no if/then/else)\n")
count = count + 1
cat("The updated count is ",count,"\n")
}
} # end loop over indices of the x vector
######################################################
# of course, there is a faster way to do this!
######################################################
cat("The elements of x that are greater than +3 are: ",which(x>3),"\n")
cat("The elements of x that are less than -3 are: ",which(x<(-3)),"\n")
######################################################
# this for loop with value y that steps through all values in the vector x.
# If you don't need to know the indices of the elements of x within the loop, this is
# another way to loop
######################################################
for (y in x){ # this is a for loop with index y that steps through all *values* in the vector x (ie; not the indices)
if (y>3.0){
cat("This element of x is greater than +3: ",y,"\n",sep="")
}else if (y<(-3.0)){
cat("This element of x is less than -3: ",y,"\n",sep="")
} # end check of value of y
} # end loop over the elements in x
######################################################
# Here is a nice trick to comment out entire blocks of code
# Because "0" is always false, the code within the curly
# brackets never gets executed
######################################################
if (0){ # this is never true, so stuff within the curly brackets won't ever run
cat("The elements of x that are greater than +3 are: ",which(x>3),"\n")
cat("The elements of x that are less than -3 are: ",which(x<(-3)),"\n")
}
######################################################
# while loops
# here we use a while loop to loop over 100 days in
# increments of 1 day
######################################################
time = 0
tend = 100
delta_time = 1
while(time<=tend){ # this gets assessed at the beginning of the loop. If the boolean in the round brackets is true, the
# code bracketed by the curly braces gets executed
if (time%%10==0){ # only print stuff out if time is divisible by 10
cat("The time right now is ",time,"\n")
}
time = time + delta_time
} # end while loop checking that time is <=tend
######################################################
######################################################
######################################################
# functions in R
# here we define a function that has three
# arguments, x slope and intercept
# we give slope a default value of 1, and intercept
# a default value of zero. When an argument
# has a default value, you don't need to include
# it in the argument list when you call the function
# But, if you have more than one argument with default
# values, you need to list them in order of how often
# you will be providing a non-default value.
######################################################
myfunc = function(x,slope=1,intercept=0){
cat("(myfunc): the slope and intercept are ",slope,intercept,"\n")
y = slope*x+intercept
intercept = 9999 # setting intercept to a value within this function will not affect its value outside the function
return(y)
} # end definition of function myfunc
######################################################
# now let's use myfunc
######################################################
x = seq(1,100,0.1) # a vector with elements 1 to 100, in steps of 0.1
slope = 2
intercept = -10
y = myfunc(x,slope,intercept)
cat(intercept,"\n") # when we set intercept to 9999 within myfunc, it didn't affect the value outside that function
yb = myfunc(x,slope) # in this case the intercept will default to zero (as defined in myfunc) because we didn't include it in arguments
yc = myfunc(x,intercept) # in this case myfunc thinks the value you passed to it in intercept is actually the slope!
# this will not return what you want! (ie; myfunc with slope=1 and intercept=-10)
yd = myfunc(x,intercept=intercept) # This, however, will work correctly
par(mfrow=c(1,1)) # make sure we only have one plot in the viewing area
plot(x,y,type="l",lwd=3) # will plot a black line with width 3
lines(x,yb,col="red",lwd=3) # will overlay a red line with width 3
lines(x,yd,col="blue",lwd=3) # will overlay a blue line with width 3
######################################################
# returning more than one thing from a function
######################################################
myfunc_b = function(x,slope=1,intercept=0){
cat("(myfunc): the slope and intercept are ",slope,intercept,"\n")
my_y = slope*x+intercept
my_dydx = rep(slope,length(x))
return(list(y=my_y,dydx=my_dydx))
} # end definition of function myfunc_b
x = seq(1,25,0.01)
a = myfunc_b(x,3,2)
plot(x,a$y)