08 Functions
08 Functions
Tyson S. Barrett
Summer 2017
Utah State University
1
Introduction
Creating a Function
Named Functions
Anonymous Functions
Conclusions
2
Introduction
3
Introduction
4
What is a Function Anyway?
5
Creating a Function
6
Creating a Function
7
Named Functions
8
Named Functions
9
Named Functions
## [1] 1.8
## [1] 1.8
10
Named Functions
For practice, we will write one more function. Let’s make a function
that takes a vector and gives us the N, the mean, and the standard
deviation.
11
Named functions
One of the first things you should note is that we included a second
argument in the function seen as na.rm=FALSE (you can have as
many arguments as you want within reason).
12
Named Functions
important_statistics(v1)
13
Named Functions
## N Mean SD
## 1 10 1.8 1.032796 14
Anonymous Functions
15
Anonymous Functions
16
Why Write Your Own?
17
Why Write Your Own?
• Looping
• Adjusting output
• Performing a special function
• Other customization
18
Looping
19
Looping
Examples in R include:
• for loops
• the apply family of functions
20
For Loops
for (i in 1:10){
mean(data[, i])
}
21
For Loops
Another example:
library(tidyverse)
data = read.csv("~/Dropbox/Teaching/R for Social Sciences/D
select(Prod1, MentalApt, PhysApt, Income, Children, SubsU
thing = list()
for (i in 1:8){
thing[[i]] = cbind(mean(data[, i]), sd(data[, i]))
}
22
For Loops
thing
## [[1]]
## [,1] [,2]
## [1,] 3.2 1.146423
##
## [[2]]
## [,1] [,2]
## [1,] 5.2 2.305273
##
## [[3]]
## [,1] [,2]
## [1,] 5.733333 1.869556
##
23
## [[4]]
For loops
I like for loops. They are easy to understand and fiddle with, after
some practice.
However, they used to be slow in R and so they have a bad
reputation.
24
The apply family
• apply()
• sapply()
• lapply()
• tapply()
25
sapply
for (i in 1:10){
mean(data[, i])
}
sapply(1:10, function(i) mean(data[, i]))
26
sapply
Can also just provide the data.frame and it assumes you want the
function (in this case mean()) applied to each variable.
sapply(data, mean)
27
lapply
lapply(data, mean)
## $Prod1
## [1] 3.2
##
## $MentalApt
## [1] 5.2
##
## $PhysApt
## [1] 5.733333
##
## $Income 28
tapply
## 0 1 2
## 53.18182 55.00000 52.50000
29
Loops with User-Defined Functions
30
Loops with User-Defined Functions
31
Loops with User-Defined Functions
lapply(data, important_statistics2)
## $Prod1
## N Mean SD
## 1 15 3.2 1.146423
##
## $MentalApt
## N Mean SD
## 1 15 5.2 2.305273
##
## $PhysApt
## N Mean SD
## 1 15 5.733333 1.869556
##
32
## $Income
Loops with User-Defined Functions
sapply(data, important_statistics2)
33
Loops with User-Defined Functions
34
Conclusions
35
Conclusions
Writing your own functions takes time and practice but it can be a
worthwhile tool in using R.
I recommend you start simple and start soon.
Ultimately, you can make your own group of functions you use often
and create a package for it so others can use them too :)
36