R for reproducible scientific analysis
Creating functions
Learning Objectives
- Be able to define a function that takes arguments.
- Be able to return a value from a function.
- Be able to write conditional statements with
if
andelse
. - Know when and how to set default values for function arguments.
- Understand why we should divide programs into small, single-purpose functions.
There are many reasons to make it easy to rerun our analyses. The gapminder data is updated periodically, and we may want to pull in that new information later and re-run our analysis again. We may also obtain similar data from a different source in the future.
In this lesson, we’ll learn how to write a function so that we can repeat a set of operations with a single command. Once we have a function that is known to work, we can use it repeatedly without worrying about how it works, just as we have used functions like min and max.
Defining a function
We define a function by assigning the output of function
to a variable. The list of argument names are contained within parentheses. Next, the body of the function–the statements that are executed when it runs–is contained within curly braces ({}
). The statements in the body are indented by two spaces. This makes the code easier to read but does not affect how the code operates.
When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function. Inside the function, we use a return statement to send a result back to whoever asked for it.
Calling our own function is no different from calling any other function.
Previously we calculated the GDP by multiplying the population and gdp per capita. Rather than specifying the dataset we want to calculate gdp for every time, let’s turn this into a function.
# Takes a dataset and multiplies the pop column with the gdpPercap column.
calcGDP <- function(dat) {
gdp<-dat$gdpPercap * dat$pop
return(gdp)
}
We define calcGDP
by assigning it to the output of function
. The list of argument names are contained within parentheses. Next, the body of the function – the statements executed when you call the function – is contained within curly braces ({}
).
We’ve indented the statements in the body by two spaces. This makes the code easier to read but does not affect how it operates.
When we call the function, the values we pass to it are assigned to the arguments, which become variables inside the body of the function.
Inside the function, we use the return
function to send back the result. This return function is optional: R will automatically return the results of whatever command is executed on the last line of the function.
#first reload the original data
gapminder <- read.csv(file="gapminder-FiveYearData.csv")
calcGDP(head(gapminder))
[1] 6567086330 7585448670 8758855797 9648014150 9678553274 11697659231
That’s not very informative. Let’s also output the information from the other columns.
# Takes a dataset and multiplies the population column with the GDP per capita column.
calcGDP <- function(dat) {
gdp <- dat$pop * dat$gdpPercap
dat <- cbind(dat, gdp)
return(dat)
}
calcGDP(head(gapminder))
Note we can specify any dataset or subset of our data.
calcGDP(gapminder[20:30,])
We can use ==
to subset data by a particular value.
head(calcGDP(gapminder[gapminder$year == 2007, ]))
We can get values for two different years using by specifying one year OR another using |
(the converse is &
)
head(calcGDP(gapminder[gapminder$year == 2007|gapminder$year == 1952, ]))
Since this is getting unwieldy to read let’s put all this subsetting into our function. When we call the function we want to specify the dataset, year(s), and country(ies).
calcGDP(gapminder, 1952,"Afghanistan")
We can also use a matching function %in%
to subset data by a range of values.
To do that, we need add some more arguments to our function so we can extract year and country.
# Takes a dataset and multiplies the population column with the GDP per capita column.
calcGDP <- function(dat, year, country) {
dat <- dat[dat$year %in% year, ]
dat <- dat[dat$country %in% country,]
gdp <- dat$pop * dat$gdpPercap
dat <- cbind(dat, gdp)
return(dat)
}
The function now takes a subset of the rows for all columns by year. It then subsets this subset by country. Then it calculates the GDP for the subset of the previous two steps. The function then adds the GDP as a new column to the subsetted data and returns this as the final result. Because we have defined all of these pieces of code in one function we can now repeat this process for any dataset.
We can now calculate the GDP for a single combination of year and country.
By using %in%
we can also give multiple years or countries to those arguments.
calcGDP(gapminder, 1952:1962,country="Afghanistan")
country year pop continent lifeExp gdpPercap gdp
1 Afghanistan 1952 8425333 Asia 28.801 779.4453 6567086330
2 Afghanistan 1957 9240934 Asia 30.332 820.8530 7585448670
3 Afghanistan 1962 10267083 Asia 31.997 853.1007 8758855797
Note that we haven’t changed our original dataset. The subsetting only occurs to the copy of the data inside the function.
dim(gapminder)
Now let’s expand this function to check whether the year and country are specified. If they aren’t then we can use all of them. We can use conditional statements to set actions to occur only if a condition or a set of conditions are met.
# if
if (condition is true) {
perform action
}
# if ... else
if (condition is true) {
perform action
} else { # that is, if the condition is false,
perform alternative action
}
A common use of an if
statement if to check is to compare values. For example: {.r} x=1001 if(x==1001){ print(‘x is 1001’) } else{ print(‘x is not 1001’) }
x=1001
if(x>1000){
print('x is greater than 1000')
} else{
print('x is not greater than 1000')
}
And if I’m coding properly I would put this in a function.
check1000<-function(x){
if(x>1000){
print(x)
print('is greater than 1000')
} else{
print(x)
print('is not greater than 1000')
}
}
check1000(1001)
For calculating gdp information we first specify the default value of year and country as NULL. We then check whether when the function is called the year or country is specified or the default value is used using an if
statement and the is.null
function.
# Takes a dataset and multiplies the population column with the GDP per capita column.
calcGDP <- function(dat, year=NULL, country=NULL) {
if(!is.null(year)) {
dat <- dat[dat$year %in% year, ]
}
if (!is.null(country)) {
dat <- dat[dat$country %in% country,]
}
gdp <- dat$pop * dat$gdpPercap
dat <- cbind(dat, gdp=gdp)
return(dat)
}
The function now subsets the provided data by year if the year argument isn’t empty, then subsets the result by country if the country argument isn’t empty. Then it calculates the GDP for whatever subset emerges from the previous two steps. The function then adds the GDP as a new column to the subsetted data and returns this as the final result. You can see that the output is much more informative than just getting a vector of numbers.
Let’s take a look at what happens when we specify the year:
head(calcGDP(gapminder, year=2007))
country year pop continent lifeExp gdpPercap gdp
12 Afghanistan 2007 31889923 Asia 43.828 974.5803 31079291949
24 Albania 2007 3600523 Europe 76.423 5937.0295 21376411360
36 Algeria 2007 33333216 Africa 72.301 6223.3675 207444851958
48 Angola 2007 12420476 Africa 42.731 4797.2313 59583895818
60 Argentina 2007 40301927 Americas 75.320 12779.3796 515033625357
72 Australia 2007 20434176 Oceania 81.235 34435.3674 703658358894
Or for a specific country:
calcGDP(gapminder, country="Australia")
country year pop continent lifeExp gdpPercap gdp
61 Australia 1952 8691212 Oceania 69.120 10039.60 87256254102
62 Australia 1957 9712569 Oceania 70.330 10949.65 106349227169
63 Australia 1962 10794968 Oceania 70.930 12217.23 131884573002
64 Australia 1967 11872264 Oceania 71.100 14526.12 172457986742
65 Australia 1972 13177000 Oceania 71.930 16788.63 221223770658
66 Australia 1977 14074100 Oceania 73.490 18334.20 258037329175
67 Australia 1982 15184200 Oceania 74.740 19477.01 295742804309
68 Australia 1987 16257249 Oceania 76.320 21888.89 355853119294
69 Australia 1992 17481977 Oceania 77.560 23424.77 409511234952
70 Australia 1997 18565243 Oceania 78.830 26997.94 501223252921
71 Australia 2002 19546792 Oceania 80.370 30687.75 599847158654
72 Australia 2007 20434176 Oceania 81.235 34435.37 703658358894
Or both:
calcGDP(gapminder, year=2007, country="Australia")
country year pop continent lifeExp gdpPercap gdp
72 Australia 2007 20434176 Oceania 81.235 34435.37 703658358894
Let’s walk through the body of the function:
calcGDP <- function(dat, year=NULL, country=NULL) {
Here we’ve added two arguments, year
, and country
. We’ve set default arguments for both as NULL
using the =
operator in the function definition. This means that those arguments will take on those values unless the user specifies otherwise.
if(!is.null(year)) {
dat <- dat[dat$year %in% year, ]
}
if (!is.null(country)) {
dat <- dat[dat$country %in% country,]
}
Here, we check whether each additional argument is set to null
, and whenever they’re not null
overwrite the dataset stored in dat
with a subset given by the non-null
argument.
We can now ask the function to calculate the GDP for:
- The whole dataset;
- A single year;
- A single country;
- A single combination of year and country.
Challenge 1
What is the expected result from the following script?
add3 <- function(y){
y+3
}
x <- 10
y <- add3(x)
print(x)
print(y)