[R] questions on unstack()

Murali.Menon at avivainvestors.com Murali.Menon at avivainvestors.com
Mon Oct 18 16:47:57 CEST 2010


Folks,

I have the following dataframe:

> x <- structure(list(name = c("EU B", "EU B", "EU B", "EU B", "EU B", 
"EU B", "AU A", "AU A", "AU A", "AU A", "AU A", "AU A"), date = c("2010-10-11", 
"2010-10-12", "2010-10-13", "2010-10-14", "2010-10-15", "2010-10-18", 
"2010-10-11", "2010-10-12", "2010-10-13", "2010-10-14", "2010-10-15", 
"2010-10-18"), Jem = c(1.3924, 1.3888, 1.3867, 1.3949, 1.4054, 
1.3992, 0.9864, 0.9859, 0.9842, 0.9919, 0.9925, 0.9901), Bim = c(1.3888, 
1.3867, 1.3949, 1.4054, 1.3977, 1.3917, 0.9859, 0.9842, 0.9919, 
0.9925, 0.9907, 0.9881)), .Names = c("name", "date", "Jem", "Bim"
), row.names = c(1L, 2L, 3L, 4L, 5L, 8L, 9L, 10L, 11L, 12L, 13L, 
16L), na.action = structure(c(6L, 7L, 14L, 15L), .Names = c("6", 
"7", "14", "15"), class = "omit"), class = "data.frame")

> x
   name       date    Jem    Bim
1  EU B 2010-10-11 1.3924 1.3888
2  EU B 2010-10-12 1.3888 1.3867
3  EU B 2010-10-13 1.3867 1.3949
4  EU B 2010-10-14 1.3949 1.4054
5  EU B 2010-10-15 1.4054 1.3977
8  EU B 2010-10-18 1.3992 1.3917
9  AU A 2010-10-11 0.9864 0.9859
10 AU A 2010-10-12 0.9859 0.9842
11 AU A 2010-10-13 0.9842 0.9919
12 AU A 2010-10-14 0.9919 0.9925
13 AU A 2010-10-15 0.9925 0.9907
16 AU A 2010-10-18 0.9901 0.9881

I'm trying to collapse the frame so that I get columns of names:

> unstack(x, Jem ~ name)
    AU.A   EU.B
1 0.9864 1.3924
2 0.9859 1.3888
3 0.9842 1.3867
4 0.9919 1.3949
5 0.9925 1.4054
6 0.9901 1.3992

Three questions:

1. The column names are converted from "EU B" to "EU.B" - how to preserve the original names?

2. The column names are sorted alphabetically - how to preserve the original order? I tried

> unstack(x, terms(Jem ~ name, keep.order = TRUE))

but it doesn't really do anything.

3. If I declare a variable wantedName <- 'Jem', how can I use it to perform the unstack:

> unstack(x, `wantedName` ~ name)
Error in tapply(eval(form[[2L]], x), eval(form[[3L]], x), as.vector) : 
  arguments must have same length


Thanks, 
Murali



More information about the R-help mailing list