library(gapminder)
data(gapminder)Exercises: Simple Functions in R
1 Simple Functions in R
1.1 Instructions and Setup
Write these functions. Run the tests.
1.1.1 Life expectancy change
Write life_change() to return life expectancy in year2 minus year1 for a country. Return NA if either year is missing.
life_change <- function(country_name, year1, year2) {
# Write code here
}
life_change("China", 1982, 2007)NULL
life_change("India", 1952, 2007)NULL
1.1.2 Compare countries
Write compare_yr() that accepts any number of country names and prints:
Country: YYYY lifeExp = __, gdpPercap = __
Each country gets its own line. Skip any countries not found.
Must specify year as an argument. Set year to 2007 by default.
Multiple countries can be passed via ....
# Note there are only a few unique years in the dataset, so we can check for valid years with unique()
unique(gapminder$year) [1] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007
compare_yr <- function(yr = 2007, ...) {
# Write code here
}
compare_yr(2002, "Norway", "Italy", "India", "Brazil")NULL