Practising R

This document shows a small piece of code to calculate average GDP for continents.

download.file("https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder_data.csv", 
              destfile = "data/gapminder_data.csv")

gapminder <- read.csv("data/gapminder_data.csv")

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
  
  new <- cbind(dat, gdp = gdp)
  return(new)
}

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
calcGDP(gapminder, year = 2007, country = "Albania")
##    country year     pop continent lifeExp gdpPercap         gdp
## 24 Albania 2007 3600523    Europe  76.423   5937.03 21376411360