Functions & Conditionals stat 480 Heike Hofmann

advertisement
Functions &
Conditionals
stat 480
Heike Hofmann
Outline
• Functions - more detailed intro:
• default parameters
• conditionals
• Practice
Functions in R
• Have been using functions a lot, now we
want to write them ourselves!
• Idea: avoid repetitive coding (errors will
creep in)
• Instead: extract common core, wrap it in a
function, make it reusable
Basic Structure
• Name
• Input arguments
•
•
names,
default values
• Body
• Output values
Conditionals
• if (condition) {
statement
} else {
statement
}
only one set of commands is
executed depending on the
result of the condition
• condition is a length one logical value, i.e. either TRUE
or FALSE
• use && and || to combine several conditions
• ! negates condition
A first function
mean <- function(x) {
return(sum(x)/length(x))
}
mean(1:15)
mean(c(1:15, NA))
mean <- function(x, na.rm=F) {
if (na.rm) x <- na.omit(x)
return(sum(x)/length(x))
}
mean(1:15)
mean(c(1:15, NA), na.rm=T)
Good Practice
• Use tabulators to structure blocks of
statements
• Build complex blocks of codes step by
step, i.e. try with single state first, try to
generalize
•#
write comments!
Function mean
• Name:
• Input arguments
•
•
mean
x, na.rm=T
names,
default values
• Body
• Output values
if(na.rm) x <- na.omit(x)
return(sum(x)/length(x))
Function Writing
• Start simple, then extend
• Test out each step of the way
• Don’t try too much at once
• help(browser)
Practice
• Pick and solve three of the function drills on
http://www.public.iastate.edu/~hofmann/stat480/
homework/function%20drills.html
Practice
• Write a function called mba
input: playerID
output: life-time batting average for playerID
• what does mba(“bondsba01”)do?
• write a function called pstats
input: playerID
output: - life-time batting average for playerID
- number of overall at bats
Checkpoint
• Submit all of your code for the last Your Turn at
http://heike.wufoo.com/forms/check-point/
Testing
• Always test the functions you’ve written
• Even better: let somebody else test them
for you
• Switch seats with your neighbor, test their
functions!
Download