knitr-Example: Use World Bank Data to Generate Report for Threatened Bird Species

May 2, 2012

(This article was first published on theBioBucket*, and kindly contributed to R-bloggers)

I’ll use the below script that retrieves data for threatened bird species from the World Bank via its API and does some processing, plotting and analysis. There is a package (WDI) that allows you to access the data easily.

# world bank indicators for species - 
# I'll check bird species:
code <- as.character(WDIsearch("bird")[1,1])
bird_data <- WDI(country="all", indicator=code, start=2010, end=2012)

# remove NAs and select values in the range 50 - 1000:
bird_data_sub <- bird_data[!$EN.BIR.THRD.NO)&
bird_data$EN.BIR.THRD.NO < 1000&
bird_data$EN.BIR.THRD.NO > 50, ]

# change in numbers across years 2010 and 2011: <- aggregate(EN.BIR.THRD.NO ~ country, diff,
data = bird_data_sub)
# plot:
par(mar = c(3, 3, 5, 1))
plot(x =[,2], y = 1:nrow(,
xlim = c(-12, 12), xlab = "", ylab = "",
yaxt = "n")
abline(v = 0, lty = 2, col = "grey80")
title(main = "Change in Threatened Bird Species in\nCountries with Rich Avifauna (>50)")
text(y = 1:nrow(,
x = -2, adj = 1,
labels =$country)
segments(x0 = 0, y0 = 1:nrow(,
x1 =[, 2], y1 = 1:nrow(

# test hypothesis that probability of species decrease is
# equal to probability of increase:
binom.test(sum( < 0), sum( != 0))

For generating the report you can source the script from and stitch it in this fashion:


..this is one line of code – can you dig it?..
BTW, for simplicity I use knitr::stitch with its default template…

You should get something like THIS PDF.

OUTDATED! you can use this approach instead:

library(knitr); library(RCurl); library(WDI)

destfile = "script.txt"
x = getBinaryURL("", followlocation = TRUE, ssl.verifypeer = FALSE)
writeBin(x, destfile, useBytes = TRUE)
source(paste(tempdir(), "/script.txt", sep = ""))

stitch(paste(tempdir(), "/script.txt", sep = ""))

To leave a comment for the author, please follow the link and comment on their blog: theBioBucket*. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)