Monday, August 19, 2013

A way to simplify package use on a R project

Introduction

Introduction

One of the steps that I always do when I begin an R script is to check if all the needed packages are installed, and if not install them.

That way I know that the script won't crash on another computer because of a missing package (one less reason to crash :D).

Lately I've been thinking about the subject of code reuse and decided to transform my block of code in to an R function.

The Code

#«««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««
#  script : loadlib.R
#  author : Vitor Chagas(VC)                last updated : 2013.08.19
#«««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««

# install & load necessary packages ----
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

loadlibs <- function(...) {

  necessary <- as.vector(as.character(match.call()[-1]))

  installed <- necessary %in% .packages(all.available = TRUE)

  # install
  if (length(necessary[!installed]) >=1)
    install.packages(necessary[!installed])

  # update
  update.packages()

  # load
  for(pkg in necessary)
    library(pkg, character.only=TRUE)  

  rm(necessary, installed, pkg)
}

Final comments

Now I just save this code into a lib folder, and then use the following code to source every code file in there

sapply(list.files(pattern="*.R", path="lib", full.names=TRUE),
       source,.GlobalEnv)

Saturday, August 10, 2013

Mapping Earthquakes Over the Past 30 Days

Introduction

Introduction

After reading this post I decided to try it and adapt to my own needs.

This is just a simple example that uses real-time data from the U.S. Geological Survey.

This shows the location of earthquakes with any magnitude over the last month around Puerto Rico (just had to pick some place with earthquakes!).

The Code


#===========================================================================
# project : aportugueseactuary.blogspot.pt
#  script : Mapping_Earthquakes_Over_the_Past30_Days.R
#  author : Vitor Chagas
# updated : 2013.08.10
#===========================================================================

#---------------------------------------------------------------------------
# reset workspace
#---------------------------------------------------------------------------

rm(list = ls())
gc()

#---------------------------------------------------------------------------
# create & set work directory root
#---------------------------------------------------------------------------

# change as needed
workdir <- '.'

dir.create(workdir, recursive=TRUE)
setwd(workdir)
rm(workdir)

#---------------------------------------------------------------------------
# create folder tree (needed folders)
#---------------------------------------------------------------------------

#dir.create('data')

#---------------------------------------------------------------------------
# install & load necessary packages
#---------------------------------------------------------------------------

necessary = c('ggmap')

installed = necessary %in% .packages(all.available = TRUE)

# install
if (length(necessary[!installed]) >=1) 
  install.packages(necessary[!installed])

# load
for(pkg in necessary) 
  library(pkg, character.only=TRUE)  

rm(necessary, installed, pkg)

#---------------------------------------------------------------------------
# get earthquake data
#---------------------------------------------------------------------------

file.url <- c(
  url='http://earthquake.usgs.gov/',
  path='earthquakes/feed/v1.0/summary/',
  file='all_month.csv'
  )

eq <- read.table(file=paste(file.url, collapse=''),
                 fill=TRUE, sep=',', header=TRUE)

# rename columns
names(eq)[2] <- 'lat'
names(eq)[3] <- 'lon'

# discretize magnitude into 5 intervals
eq$mag.size <- findInterval(eq$mag, c(0,2,4,6,8,10))

#---------------------------------------------------------------------------
# generate map
#---------------------------------------------------------------------------

# map center (some place with earthquakes)
center <- geocode('Puerto Rico')
location <- c(center$lon,center$lat)

# get map from Google
map <- get_map(location = location, zoom=7, maptype='roadmap')

# display earthquake data
ggmap(map, extent = 'device') +
  geom_point(data=eq,
             mapping=aes(x = lon, y = lat, colour=mag)) + 
  scale_colour_gradient(limits=c(0, 9.9), low="yellow", high="red")

plot of chunk unnamed-chunk-1

Conclusions

The process is very simple, but sometimes it needs some fine tune of the zoom and maptype options to get the intended result.

This data source is not enough for my own needs, it's not picking the earthquakes around Portugal, so I need to find an alternative.

Sunday, July 14, 2013

Blogging with R Markdown

Introduction

Introduction

This is just an experiment on using the R Markdown facility in RStudio to obtain a simpler blogging workflow for Blogger.

Step 1. Create a new folder tree

It's a good practice to create an dedicated folder tree for the post, after all, is just like starting a new small project.

Create any extra folder you think you might need, for instance an image folder to put any image needed that is not an R plot (those will be automatically saved in a figure folder).

alt text

Step 2. Write your post in R Markdown

!!!This is the just the R Markdown template!!!

This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages (click the MD toolbar button for help on Markdown).

When you click the Knit HTML button a web page will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist    
##  Min.   : 4.0   Min.   :  2  
##  1st Qu.:12.0   1st Qu.: 26  
##  Median :15.0   Median : 36  
##  Mean   :15.4   Mean   : 43  
##  3rd Qu.:19.0   3rd Qu.: 56  
##  Max.   :25.0   Max.   :120

You can also embed plots, for example:

plot(cars)

plot of chunk unnamed-chunk-2

Step 3. Knit HTML

Press the Knit HTML button and a Preview HTML window will appear so the result can be checked.

alt text

By now the folder tree has new files and folders.

alt text

Step 4. Copy HTML into Blogger

Open in Editor the resulting HTML file and copy all of it into Blogger.