Question

I'm trying to convert a data.frame to a zoo object using read.zoo. It all seems to work fine except that the original index contains years only (no months or days) and yet when I read it in they appear.

Is there a way to create the new object with index as years only?

test.df3 <- data.frame (Country = rep (c (1, 5000), each = 10),
                        Year = factor(rep(1990:1999, 2)),
                        Values = sample(x =  1:20, size = 20, replace = TRUE),
                        Weights = sample (x = seq (0,50,10), size = 20,
                                          replace =TRUE)
                       )
stuff <- read.zoo (test.df3, format = "%Y", index.column = 2)

This is what I get:

> head(stuff)
           Country Values Weights
1990-01-10       1      2      50
1990-01-10    5000     19       0
1991-01-10       1     10      30
1991-01-10    5000      3      20

This is what I hope to get:

> head(stuff)
           Country Values Weights
1990             1      2      50
1990          5000     19       0
1991             1     10      30
1991          5000      3      20
Was it helpful?

Solution

Specifying format and no FUN or tz causes the heuristic to assume you want a "Date" class index. Specify FUN=identity to have no conversion and omit the format=. Also it seems that there are time series for two countries intermixed so we can split them, each into their own series, using split=.

read.zoo(test.df3, index = "Year", split = "Country", FUN = identity)

which gives:

     Values.1 Weights.1 Values.5000 Weights.5000
1990        6        50           2           30
1991       14        20           7           50
1992        7        40           6            0
1993       18        30          17           20
1994       10        50          13            0
1995        3         0          17           40
1996        4        20          16           40
1997       20        20          18           20
1998        9        20          16           30
1999       20         0          15           30
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top