Skip to content

Posts from the ‘Software’ Category

R Style Guide


useR! logo

Having a systematic and consistent guide is important for programming, so does in R.

Here are some recommended style guides for programming in R.

Pick one of them and strictly follow it.

[update] There is a research showing that underscore  allow programmers tracking the code easier. (link)

1. Google’s R Style Guide

  • Link to Google’s R Style Guide (official URL, pdf)
  • Providing 14 R Style Rules including filenames, identifiers, indentation, spacing etc.
    “These rules were designed in collaboration with the entire R user community at Google”

2. Henrik Bengtsson’s R Coding Conventions

  • Link to R Coding Conventions
  • Developed since 2002. It’s version 0.9 (January 2009)
  • Please read this message in the introduction part before applying this coding convention.

” Please note that this document is under construction since mid October 2002 and should still be seen as a first rought draft.  There is no well defined coding recommendations for the R language [1] and neither is there a de facto standard. This document will give some recommendations, which are very similar to the ones in the Java programming style [2][3], which have found to be helpful for both the developer as well as the end user of packages and functions written in R.

3. Hadley Wickham’s Style Guide

Here is what he mentions in the introduction.
“Good coding style is like using correct punctuation when writing: you can manage without it, but it sure makes things easier to read. As with punctuation, there are many possible variations, and the main thing is to be consistent. The following guide describes the style that I use – you don’t have to use it, but you need to have some consistent style that you do follow. My style is based on Google’s R style guide, with a few tweaks.Good style is important because while your code only has one author, it will usually have multiple readers, and when you know you will be working with multiple people on the same code, it’s a good idea to agree on a common style up-front.”

4. R Core’s coding standard

5. formatR package

  • Links to the package’s CRAN GitHub site
  • One can also use Yihui’s formatR package to tidy R codes with function tidy.source().
  • Package description is as follows

“The formatR package was designed to reformat R code to improve readability; the main workhorse is the function tidy.source(). Features include:

  • long lines of code and comments are reorganized into appropriately shorter ones
  • spaces and indent are added where necessary
  • comments are preserved in most cases
  • the number of spaces to indent the code (i.e. tab width) can be specified (default is 4)
  • an else statement in a separate line without the leading } will be moved one line back
  • = as an assignment operator can be replaced with <-"

6. The State of Naming Conventions in R

by Rasmus Bååth in The R Journal (pdf)
(Added on 15 December 2012)

More posts about R

Testing R Markdown with R Studio and posting it on RPubs.com


Today R Studio has announced  RPubs.com, a new platform to publish an R Markdown document in html format.

It seems that RStudio is a very fast growing IDE for not only data analysis in R but also for reproducible report in PDF and HTML using R and knitr package.

I then tried to create an R Markdown file  with R Studio for my recent data visualisation for Thai tourist data.

And here is my first published HTML report using R Markdown with RStudio.

The following is the code in the R Markdown file.


Visualising International Tourist Arrival
========================================================

by **Pairach Piboonrungroj**
email: <me@pairach.com>
twitter: [@piboonrungroj](https://twitter.com/#!/Piboonrungroj)

This is a test for an R Markdown document using my analysis of *tourist data of Thailand*.
You may see the original post in [my website](https://pairach.com/2012/05/31/using-r-to-analysis-tourism-data-1/)

Tourism is an important sector in the global economy. In many countries, tourism is the main source of revenue, Thailand is one of them. However, tourism sector is a fast moving sector. It is very sensitive to various factors and also vulnerable. The tourism markets for each destination (country) are also very diverse. Tourism data are available and updated frequently. One of the most important report of national tourism statistics; number of tourist arrivals from each country of origin, their average length of stay and total receipt or expenditure. These tourism statistics are important but often reported separately due to the limitation of software used by analysts.

The following are the steps to produce a comprehensive profile of international tourists in Thailand in 2005 with ggplot2 package in R.

### 1: Import data into R
```{r}
exp05 <- read.csv("http://dl.dropbox.com/u/46344142/thai_tour_2005.csv", head = T)
```

### 2: Load 'ggplot2' package for plotting elegant data visualisation
```{r}
library(ggplot2)
```

### 3: Specify x and y axis, label, size of the bubbles and colour of the region
```{r fig.width=7, fig.height=6}
exp <- ggplot(exp05, aes(x=number, y=length, label=country, size=receipt, colour = region))
```

### 4: Create a plot and add texts to x and y axis
```{r fig.width=11, fig.height=6}
exp + geom_point() + geom_text(hjust=0.7, vjust=2) + labs(x = "Number of Tourist Arrivals", y = "Length of Stay (days)") + scale_area("Receipt (M. USD)") + scale_colour_hue("Region")
```

Resources for Structural Equation Model (SEM)


This post lists some SEM resources available to learn online.
As I am adding and updating the list, if you know more useful resource  for SEM please leave then in the comments., Thank you 🙂

Tutorials

  1. SEM tutorial
    by David A. Kenney
  2. Wikia-Psychology
    Structural Equation Modeling including steps in performing SEM
  3. An Introduction to Structural Equation Modeling for Ecology and Evolutionary Biology
    by Jjarrett Byrnes

Software to fit SEM

  1. List of R packages for Structural Equation Model [url]
  2. SEM
    – Uses of packages in R (sem, OpenMx)
    Edinburgh R user group

Miscellaneous 

  • Prof. Karl Joreskog’s story by David Burns [url]

Using R to Analyse Tourism Data – Part 1: Visualising Tourist Profile


Tourism is an important sector in the global economy. In many countries, tourism is the main source of revenue, Thailand is one of them. However, tourism sector is a fast moving sector. It is very sensitive to various factors and also vulnerable. The tourism markets for each destination (country) are also very diverse. Tourism data are available and updated frequently. One of the most important report of national tourism statistics; number of tourist arrivals from each country of origin, their average length of stay and total receipt or expenditure. These tourism statistics are important but often reported separately due to the limitation of software used by analysts.

The following graph represents profile of international tourists in Thailand in 2005.

The picture above was produced in R with package ‘ggplot2’ using the code below.


# Step 1: Import data into R
exp05 <- read.csv("http://dl.dropbox.com/u/46344142/thai_tour_2005.csv", head = T)
# Step 2: Load 'ggplot2' package for plotting elegent data visualisation
library(ggplot2)
# Step 3: Specify x and y axis, label, size of the bubbles and colour of the region
exp <- ggplot(exp05, aes(x=number, y=length, label=country, size=receipt, colour = region))
# Step 4: Create a plot and add texts to x and y axis
exp + geom_point() + geom_text(hjust=0.7, vjust=2) + labs(x = "Number of Tourist Arrivals", y = "Length of Stay (days)") + scale_area("Receipt (M. USD)") + scale_colour_hue("Region")

Measuring Emergency Relief Performance of Thailand Floods in 2011


Background

Last year Thailand faced the worst floods in their history. The World Bank (2011) reported that the 2011 Thailand floods were “The biggest damages and losses were in the manufacturing sector, with a total of THB 1,007 Bn (USD 32 Bn approximately)”. The tourism and agricultural sector were also affected and losses approximately THB 95 Bn (USD 3 Bn) and THB 40 Bn (USD 1.3 Bn) respectively (The World bank, 2011).

Therefore, this study aims to evaluate the performance of organisations that took actions in emergency relief for this disaster. We measure performance based on their preparedness for such disaster as well as how they responded to the events. Data collected via GoogleDoc from 382 respondents (victims) were (A) explored and the (B) used to fit with the conceptual model of performance measurement for emergency relief logistics.

A. Preliminary Findings

  • Descriptive_GoogleDoc (in Thai)
    A chart below shows the proportion of organisations, which samples have got helps.
    Highest percentage is unknown organisation, followed by military agencies.
  • Interesting Info-graphic obtained using R

What we can get from R

Moving away from the basic barplot instantly provided by Google Doc, we can do a better job to visualise what  people rate the performance of each organisation in terms of preparedness and response to the floods. An we can do so via R. Followings are what I produced in R.

1. Level Preparedness 

# Boxplot preparedness performance

k <- ggplot(flood, aes(factor(org), aPRE))

k + geom_jitter(aes(colour = org), size = 4) + opts(legend.title = theme_text(size = 20, face = "bold"), legend.text = theme_text(size = 10)) + opts(title = "Level of Perceived Preparedness of each Organisation") + opts(plot.title = theme_text(size = 15, face="bold", colour = "blue"))

2. Level of Responses

# Boxplot response perforance

c <- ggplot(flood, aes(factor(org), aRES))

c + geom_jitter(aes(colour = org), size = 4) + opts(legend.title = theme_text(size = 20, face = "bold"), legend.text = theme_text(size = 10)) + opts(title = "Level of Perceived Response of each Organisation") + opts(plot.title = theme_text(size = 15, face="bold", colour = "blue"))
<pre>

B. Theoretical Output: BAM2012 Paper

Title: Developing Measurement of Emergency Relief Logistics and Operations Performance: An Empirical Study of Thailand Floods in 2011

Summary

Albeit emergency relief logistics is an emerging field in operations, logistics and supply chain management, the development of performance measurement is still limited. Although one of the objectives of emergency relief logistics is to satisfy customers (victims in the disaster) the development of performance measurement based on victim’s perspective is limited. Then this study propose a measurement of emergency relief logistics performance and tested with an empirical data from the Thailand floods in 2011. We fit the propose measurement model with the data of 382 respondents using Confirmatory Factor Analysis with Mplus version 6 and R version 2.14.1. The result shows that the model is fit with the data. It was found that response had the highest contribution to the total performance, followed by preparedness and recovery respectively. The result also shows that information, operations and evacuation have different contribution to the performance of each stage.

Keywords: Humanitarian logistics, Emergency relief, disaster, floods, Thailand

Download: pdf

R code used in the paper

</pre>
library(lavaan)
 flood1.cfa <-'

PRE =~ x411 + x412 + x413 + x414 + x415 + x416
 + x421 + x422 + x423 + x424 + x425
 + x431 + x432 + x433 + x434

RES =~ x511 + x512 + x513 + x514 + x515 + x516
 + x521 + x522 + x523 + x524 + x525 + x526 + x527
 + x531 + x532 + x533 + x534 + x536

REC =~ x611 + x612 + x613 + x614 + x615 + x616 + x617
 + x621 + x622 + x623 + x624 + x625 + x626 + x627
 + x631 + x632 + x633 + x634 + x636

PEF =~ PRE + RES + REC

'
 fitFlood1 <- cfa(flood1.cfa, data=flooddata)
 summary(fitFlood1, standardized=TRUE, fit.measures=TRUE)
<pre>