1
votes

I have a zoo object with three columns. I want to calculate pairwise differences for each column to get the relative change over time. I'm using a for-loop for this. However, what I get returned isn't a zoo object anymore but a normal data.frame.

When I want to plot it in multiple panels, I loose my x-axis time labels. When I try to transform the dataframe back into a zoo object, I get an error of "bad entries"

head(zoo.2017)

          zoo1  zoo2     zoo3
2017-01-01 104.6066 106.6240 112.7336
2017-01-02 103.1034 104.4088 111.8473
2017-01-03 103.4550 107.0606 111.4292
2017-01-04 101.6916 108.0550 111.8183
2017-01-05 101.8274 105.1528 114.3505
2017-01-06 102.9502 107.1381 113.8313

delta<-zoo()

for(n in 2:length(zoo.2017[,1])){

    diff<-as.data.frame(zoo.2017[n,])-as.data.frame(zoo.2017[n-1,])
    delta<-rbind(delta, diff)
}

head(delta)
               Maui6   Olowalu        Pali
 diff       -1.503264 -2.215139  -0.8862847
 2017-01-03 0.3516667  2.651771  -0.4180556
 2017-01-04 -1.763472 0.9944444   0.3890625
 2017-01-05 0.1358681 -2.902257    2.532153
 2017-01-06  1.122743  1.985313  -0.5191319
 2017-01-07  1.430937 0.5648958 -0.01836806

I know the error probably comes from the as.data.frame() in the for loop, but I don't know how else to compute it. When I try an read.zoo() on the dataframe afterwards, it gives me the bad entries error...

I'm still having a hard time with zoo

1
Please give us dput(head(zoo.2017)) - ngm
And doesn't diff(zoo.2017) just give you what you want anyway? - ngm
It does, thank you! I'm not yet too familiar with all the possibilities of zoo. I didn't know about this - Anke

1 Answers

0
votes

If z is the zoo object defined reproducibly in the Note at the end then to get successive differences in each column use diff.zoo

zd <- diff(z)

giving this zoo object:

> zd
              zoo1    zoo2    zoo3
2017-01-02 -1.5032 -2.2152 -0.8863
2017-01-03  0.3516  2.6518 -0.4181
2017-01-04 -1.7634  0.9944  0.3891
2017-01-05  0.1358 -2.9022  2.5322
2017-01-06  1.1228  1.9853 -0.5192

Regarding plotting, we can now plot it using any of these:

plot(zd)

library(ggplot2)
autoplot(zd)

library(lattice)
xyplot(zd)

zoo comes with several vignettes (pdf documents) and a reference manual which you can read for more information.

Note

Lines <- "date,zoo1,zoo2,zoo3
2017-01-01,104.6066,106.6240,112.7336
2017-01-02,103.1034,104.4088,111.8473
2017-01-03,103.4550,107.0606,111.4292
2017-01-04,101.6916,108.0550,111.8183
2017-01-05,101.8274,105.1528,114.3505
2017-01-06,102.9502,107.1381,113.8313"
library(zoo)
z <- read.csv.zoo(text = Lines)