Reputation: 53
How can I convert the following a data frame (panel data) to zoo? let df indicates my data frame;
Ctry year Carx Brx
A 2000 23 12
A 2001 18 16
A 2002 20 20
A 2003 NA 18
A 2004 24 NA
A 2005 18 12
B 2000 NA 22
B 2001 NA 20
B 2002 NA 14
B 2003 NA NA
B 2004 18 NA
B 2005 16 14
C 2000 NA NA
C 2001 NA 25
C 2002 24 32
C 2003 21 NA
C 2004 NA 15
C 2005 24 NA
I have tried the following code
df.zoo=zoo(df[,-2], order.by=as.Date(strptime(as.character(df[,2]), "%Y")))
I obtain the following result with a warning: "some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique"
year Ctry Carx Brx
2000-06-02 A 23 12
2000-06-02 B NA 22
2000-06-02 C NA NA
.. .. .. ..
What is the most suitable form of conversion for the above data frame to perform functions in zoo package?
many thanks for your help...
Upvotes: 2
Views: 1197
Reputation: 269664
zoo with split We cannot have zoo objects which look like the sample output in the question; however, if we change the question to require a wide form time series we can use read.zoo
with the split
argument:
z <- read.zoo(DF, split = "Ctry", index = "year", FUN = identity)
giving:
> z
Carx.A Brx.A Carx.B Brx.B Carx.C Brx.C
2000 23 12 NA 22 NA NA
2001 18 16 NA 20 NA 25
2002 20 20 NA 14 24 32
2003 NA 18 NA NA 21 NA
2004 24 NA 18 NA NA 15
2005 18 12 16 14 24 NA
two zoo objects Alternately, consider creating two zoo objects:
Carx.z <- read.zoo(DF[, -3], split = "Ctry", index = "year", FUN = identity)
Brx.z <- read.zoo(DF[, -4], split = "Ctry", index = "year", FUN = identity)
giving:
> Carx.z
A B C
2000 12 22 NA
2001 16 20 25
2002 20 14 32
2003 18 NA NA
2004 NA NA 15
2005 12 14 NA
> Brx.z
A B C
2000 23 NA NA
2001 18 NA NA
2002 20 NA 24
2003 NA NA 21
2004 24 18 NA
2005 18 16 24
Note: In the development version of zoo read.zoo
is able to figure out the FUN = identity
part automatically so that argument could be dropped.
Reproducible test data. We used the following data frame DF
in the above:
Lines <- "Ctry year Carx Brx
A 2000 23 12
A 2001 18 16
A 2002 20 20
A 2003 NA 18
A 2004 24 NA
A 2005 18 12
B 2000 NA 22
B 2001 NA 20
B 2002 NA 14
B 2003 NA NA
B 2004 18 NA
B 2005 16 14
C 2000 NA NA
C 2001 NA 25
C 2002 24 32
C 2003 21 NA
C 2004 NA 15
C 2005 24 NA
"
DF <- read.table(text = Lines, header = TRUE)
Upvotes: 1