[R] Compute correlation matrix for panel data with specific ordering
Dieter Menne
dieter.menne at menne-biomed.de
Sat Jun 27 12:34:01 CEST 2009
Serguei Kaniovski <Serguei.Kaniovski <at> wifo.ac.at> writes:
>
> df <-
>
data.frame(cbind(rep(c("AUT","BEL","DEN","GER"),4),
cbind(rep(c(1999,2000,2001,2002),4)),sample(10,16,replace=T)))
> names(df) <- c("country","year","x")
>
> SORT <- c("GER","BEL","DEN","AUT")
>
> I need to compute the correlation between countries in the variable "x"
> in such a way that the rows & columns of the resulting correlation
> matrix are not in an alphabetical order but in the order of a given
> factor vector - here SORT.
>
This boils down to : how do I reorder a factor not to use alphabetical order?
There are several reorders around, and you could do it with base function in R,
but I find the following solution using package gdata the most readable:
library(gdata)
df <- data.frame(country = sample(c("AUT","BEL","DEN","GER"),10,TRUE))
str(df)
SORT <- c("GER","BEL","DEN","AUT")
df$countryS = reorder(df$country, new.order=SORT)
Dieter
More information about the R-help
mailing list