Showing posts with label R. Show all posts
Showing posts with label R. Show all posts

Monday, October 12, 2009

Multiple graphics windows in R

I have been thinking for the longest time that R could only handle one graphics windows, I should have looked a little deeper. It turns out that it is very easy to do.

To create a new window, simply type: windows() or X11(). This will open a new graphics device and give it the next available number.
To make window k the active window, the command is windows(k).
To close window k, dev.off(k) is the way to go.

For more commands and information, see help(dev.cur) in Rgui.

Saturday, August 22, 2009

Selectively removing objects in R

Suppose you have created a bunch of objects but want to keep only a, b, and c. You can do the following:

# Create an character vector with the objects to keep:

keepthis<-c("a", "b","c")

# Use the set operator setdiff() to delete only the difference
# between the set objects() and the set keepthis.

rm(list=c(setdiff(objects(), keepthis)))

#You can progressively add objects to keepthis using append():

keepthis<-append(keepthis,c("d", "e"))

Friday, August 21, 2009

Transposing a Dataset


# A common problem is to transpose a dataset from the long to the wide
# format,e.g., given the dataset below:
> s <- c("a","b","c") # Set up a group of source
> d <- expand.grid(s,s) # Create the cartesian product of s
> d$flow <- ifelse(d$Var1==d$Var2,0,0.2534469)# Assign the values
> print(d)
Var1 Var2 flow
1 a a 0.0000000
2 b a 0.2534469
3 c a 0.2534469
4 a b 0.2534469
5 b b 0.0000000
6 c b 0.2534469
7 a c 0.2534469
8 b c 0.2534469
9 c c 0.0000000
#we would like something like this:
# Var2
#Var1 a b c
# a 0.0000000 0.2534469 0.2534469
# b 0.2534469 0.0000000 0.2534469
# c 0.2534469 0.2534469 0.0000000
#The function reshape() is handy for this, but more often than not is
#cumbersome to use. The package reshape with the functions cast() and
#melt() is way more intuitive. An alternative way takes advantage of
#R's vectorization function tapply():
> tapply(d[,3],d[,c(1,2)],c)
Var2
Var1 a b c
a 0.0000000 0.2534469 0.2534469
b 0.2534469 0.0000000 0.2534469
c 0.2534469 0.2534469 0.0000000
# contrast the tapply version with the reshape one:
> reshape(d, idvar="Var1",timevar="Var2",direction="wide")
Var1 flow.a flow.b flow.c
1 a 0.0000000 0.2534469 0.2534469
2 b 0.2534469 0.0000000 0.2534469
3 c 0.2534469 0.2534469 0.0000000

Tuesday, August 11, 2009

Sophisticated axis labels in R

Sometimes you need to put Greek letters or simply a sub index in an axis label of a plot. You could do the following:
xlab=expression(paste("US Markets",~~(omega[kt]),sep=""))
where omega is, well, omega, and [kt] will put a subindex kt. It works for ylab, main, etc.

Monday, August 3, 2009

Maps in R

The maptools package in R allows plotting data in a map --- besides keeping your work in only one environment, it saves you the like 10 minutes it takes for ArcGIS just to open, and the 10 minutes that it takes to render the map each time you modify something.

I have here a little example plotting percapita gdp growth in the world (data from the World Band Development Indicators Online). The final map looks like this (the code is below):




## read gdp growth in 2007 originally taken from the World Bank Development Indicators On-line:
dat<-read.table("http://web.ics.purdue.edu/~nvillori/blog/gdpgrowth2007.txt",header=TRUE)
## Load package maptools --- wrld_simpl is a polygon map of the world included in this package.
require(maptools)
data(wrld_simpl)
## Index ctry.names by position in the map.
dat$pos<-match(dat$Country.Code,unique(wrld_simpl$ISO3))
dat<-dat[order(dat$pos),]
## Classes & Palettes: Use packages RColorBrewer for cool palettes and classInt for easy sectioning of the values to be mapped:
### Variable to be plotted
plotvar <- dat$YR2007
### Palettes and intervals:
require(RColorBrewer)
nclr<-9
plotclr <- brewer.pal(nclr,"YlOrRd")
require(classInt)
class <- classIntervals(plotvar, nclr, style="pretty")
colcode <- findColours(class, plotclr)
### Define margins and other graphic parameters:
par(mar=c(1,1,1,1), lheight = .8)
### Plot an "empty" map with borders in grey --- aspect ratio is modified to distort image a bit:
plot(wrld_simpl,axes=TRUE,border="darkgrey",xlim=c(-110,150),bg="lightcyan", ylim=c(-45,60),asp=1.5,main="GDP Growth in 2007")
### Plot the gdp growth rates:
plot(wrld_simpl[wrld_simpl$ISO3 %in% dat$Country.Code,],col=colcode,axes=TRUE,add=TRUE)
### Add country codes to the map:
text(wrld_simpl$LON[wrld_simpl$ISO3 %in% dat$Country.Code],wrld_simpl$LAT[wrld_simpl$ISO3 %in% dat$Country.Code],wrld_simpl$ISO3[wrld_simpl$ISO3 %in% dat$Country.Code],cex=.4,col="black")
### Add a legend:
legend(title="GDP growth",-45, -15, legend=names(attr(colcode, "table")), fill=attr(colcode, "palette"), cex=.6, bty="y",bg="lightgrey")


Friday, July 31, 2009

Creating Dummy Matrices in R

The following R function creates a matrix of dummy variables. You can access the R code here, and the associated description with the example here.
This is possibly not the most efficient way of creating dummy variables, but it works for what I care.

Thursday, July 30, 2009

Currently Using

Maybe it would be a good idea for all of us to share what freeware we currently use/endorse. Feel free to post yours in the comment section.

1. TeXnicCenter
2. R through JGR (Jaguar) - I prefer to TinnR just because I like it.
3. JabRef - I can't say enough good things about this citation manager.
4. Zotero Firefox extension - This is a really easy way to get references in BibTex form. It does a great job of recognizing sources on a page full of things. Like an entire page of google scholar results or an amazon.com search.

Also, I'm sure almost everyone knows you can output references in BibTex format from googlar scholar (under scholar preferences), but if not, I thought it was worth mentioning.

Installing all Econometrics packages

We all know how much of a pain it is the install a new version of R because it loses all previously downloaded packages. This is where " task views" come into play. You can download and install all econometrics related packages by simply installing the "Econometrics" task view (see related link on the right for a list of the packages).

This is how you do it:
1. install package "ctv"
2. Type in the GUI:
library(ctv)
install.views("Econometrics")


That's it. It will take a little while!

Note for the spatial people: the task view "Econometrics" does not include spdep

Bridging the Gap Between R and SAS

One of the books that was suggested to us at AAEA was R for SAS and SPSS Users by R.A. Muenchen. You can download a free (earlier) version of the book at http://rforsasandspssusers.com/. This could help us communicate better with our current or future colleagues.

Wednesday, July 29, 2009

Using formulas in your own code

The next four lines of code allow you to create your vector y (dependent variable) and matrix X of explanatory variables from a formula and a data.frame.

#creation of an object of class "terms" decomposing the formula into a usable form
trm <- terms(formula,data=data)

#creation of a model.frame i.e. a data.frame corresponding to the formula
modelfrm <- lm(formula,data,method="model.frame")

#extraction of the dependent variable
y <- model.extract(modelfrm,"response")

#extraction of the independent variables
X <- model.matrix(trm,modelfrm)

For substituting zeroes for NAs in a dataframe

For substituting zeroes for NAs in a dataframe:

x[is.na(x)] <- 0