Showing posts with label Reproducible research. Show all posts
Showing posts with label Reproducible research. Show all posts

Sunday, September 20, 2015

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

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[!is.na(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:
change.no <- aggregate(EN.BIR.THRD.NO ~ country, diff,
data = bird_data_sub)
# plot:
par(mar = c(3, 3, 5, 1))
plot(x = change.no[,2], y = 1:nrow(change.no),
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(change.no),
x = -2, adj = 1,
labels = change.no$country)
segments(x0 = 0, y0 = 1:nrow(change.no),
x1 = change.no[, 2], y1 = 1:nrow(change.no))

# test hypothesis that probability of species decrease is
# equal to probability of increase:
binom.test(sum(change.no < 0), sum(change.no != 0))
For generating the report you can source the script from dropbox.com and stitch it in this fashion:
stitch("http://dl.dropbox.com/s/ga0qbk1o17n17jj/Change_threatened_species.R")
..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.

EDIT, MARCH 2013
OUTDATED! you can use this approach instead:

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

destfile = "script.txt"
x = getBinaryURL("https://dl.dropbox.com/s/ga0qbk1o17n17jj/Change_threatened_species.R", followlocation = TRUE, ssl.verifypeer = FALSE)
writeBin(x, destfile, useBytes = TRUE)
source(paste(tempdir(), "/script.txt", sep = ""))

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

Reproducible Research: Export Regression Table to MS Word

Here's a quick tip for anyone wishing to export results, say a regression table, from R to MS Word:


require(R2wd)

# install packages required
# install software RCOM, RDCOMClient
# (I had to restart the R-Session after the above step to get it work)

wdGet()

# Regression:
data(iris)
mod <- lm(Sepal.Length ~ Species, data = iris)
regr_tab <- data.frame(summary(mod)$coefficients)
colnames(regr_tab) <- colnames(summary(mod)$coefficients)
regr_tab[ ,4] <- ifelse(regr_tab[ ,4] < .001, "< 0.001",
ifelse(regr_tab[ ,4] < .01, "< 0.01",
round(regr_tab[ ,4], 3)))

# print table to doc in word-default format:
wdTable(format(regr_tab), autoformat = 1)

wdSave("Regression.doc") # save file
wdQuit() # close file

ps: Also check odfWeave
- this also seems to be a very useful resource!
Read more »

Reproducible Research: Running odfWeave with 7-zip

odfWeave is an R-package that is used for making dynamic reports by Sweave processing of Open Document Format (ODF) files. For anyone new to report generation and lacking knowledge of markup languages this might be a good starting point or even a true alternative to sweave / LATEX and others.

Now, anyone who recently tried to install the required zipping program for odfWeave might have noticed that there are currently no info-zip executables available (zip and unzip by info-zip software are suggested in the odfWeave manual). There are several other free zipping programs - but if you use these the default syntax for odfWeave changes. Looking into the internals it is revealed that the OS command specified for running the zipping program has to be adapted. There are some postings on the R-help mailing list concerning these topic, but none of them worked for me. After some trial and error I managed to get around this problem by using 7-zip with an adapted syntax and will share this here:


# write an in-file and save it to a folder:
dir()
[1] "Example_1_in.odt"

# testing the :
system("\"C:\\Program Files\\7-Zip\\7z.exe\" t -tzip Example_1_in.odt")

7-Zip 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18

Processing archive: Example_1_in.odt

Testing mimetype
Testing Configurations2\statusbar
Testing Configurations2\accelerator\current.xml
Testing Configurations2\floater
Testing Configurations2\popupmenu
Testing Configurations2\progressbar
Testing Configurations2\menubar
Testing Configurations2\toolbar
Testing Configurations2\images\Bitmaps
Testing content.xml
Testing manifest.rdf
Testing styles.xml
Testing meta.xml
Testing Thumbnails\thumbnail.png
Testing settings.xml
Testing META-INF\manifest.xml

Everything is Ok

Folders: 7
Files: 9
Size: 30139
Compressed: 9572

# setting up cmd prompt:
library(odfWeave)
ctrl <- odfWeaveControl(zipCmd =
c("\"C:\\Program Files\\7-Zip\\7z.exe\" a $$file$$",
"\"C:\\Program Files\\7-Zip\\7z.exe\" x -tzip $$file$$"))
# running:
odfWeave("Example_1_in.odt", "Example_1_out.odt", control = ctrl)

Copying Example_1_in.odt
Setting wd to C:\Users\Kay\AppData\Local\Temp\RtmpghYef5/odfWeave2223195249
Unzipping ODF file using "C:\Program Files\7-Zip\7z.exe" x -tzip "Example_1_in.odt"

7-Zip 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18

Processing archive: Example_1_in.odt

Extracting mimetype
Extracting Configurations2\statusbar
Extracting Configurations2\accelerator\current.xml
Extracting Configurations2\floater
Extracting Configurations2\popupmenu
Extracting Configurations2\progressbar
Extracting Configurations2\menubar
Extracting Configurations2\toolbar
Extracting Configurations2\images\Bitmaps
Extracting content.xml
Extracting manifest.rdf
Extracting styles.xml
Extracting meta.xml
Extracting Thumbnails\thumbnail.png
Extracting settings.xml
Extracting META-INF\manifest.xml

Everything is Ok

Folders: 7
Files: 9
Size: 30139
Compressed: 9572

Removing Example_1_in.odt
Creating a Pictures directory

Pre-processing the contents
Sweaving content.Rnw

Writing to file content_1.xml
Processing code chunks ...

'content_1.xml' has been Sweaved

Removing content.xml

Post-processing the contents
Removing content.Rnw
Removing styles.xml
Renaming styles_2.xml to styles.xml
Removing manifest.xml
Renaming manifest_2.xml to manifest.xml
Removing extra files

Packaging file using "C:\Program Files\7-Zip\7z.exe" a "Example_1_in.odt"

7-Zip 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Scanning

Creating archive Example_1_in.odt

Compressing Configurations2\accelerator\current.xml
Compressing content.xml
Compressing manifest.rdf
Compressing META-INF\manifest.xml
Compressing meta.xml
Compressing mimetype
Compressing settings.xml
Compressing styles.xml
Compressing Thumbnails\thumbnail.png

Everything is Ok
Copying Example_1_in.odt
Resetting wd
Removing C:\Users\Kay\AppData\Local\Temp\RtmpghYef5/odfWeave2223195249

Done

# see the result:
dir()
[1] "Example_1_in.odt" "Example_1_out.odt"
Read more »

Saturday, September 19, 2015

Playing with knitr: Create Report with Dynamic List

Here is a little toy example using knitr, LaTeX/MiKTeX and Google Docs.
Say you had a list on Google Docs (say a list of attendants) and you want to print a report with it..
Then see this example using this Rnw-file and the output...

make the tex-file with:
library(knitr)
knit("knitr_list_of_attendants.Rnw")
..then compile the tex-file with MiKTeX.

or with this shortcut:
knit2pdf("knitr_list_of_attendants.Rnw")
browseURL("knitr_list_of_attendants.pdf")

Read more »