Question

I have monthly data frame(stn) which I want convert into a single column (date vs rain) time series zoo object as it is with missing years. I would like to do few analysis with zoo package. Any help?

> head(stn)

  Year   Jan   Feb   Mar   Apr  May Jun Jul Aug Sep Oct   Nov   Dec

1 1990  79.6 168.6 122.6 161.9  0.0   0   0   0   0 0.0  11.2  45.4

2 1991 155.6 173.9 163.2  37.4  0.0   0   0   0   0 0.0   0.0  47.2

3 1995  97.7  84.9 117.1   0.0  3.6   0   0   0   0 0.4   0.0  99.8

4 1996 188.8 155.9 214.3  25.3  0.0   0   0   0   0 0.0   0.0 134.3

5 1997  37.3 202.1  24.4  21.4 39.0   0   0   0   0 0.0 120.2 372.1

6 1998 209.4 175.1 117.4 135.4  5.2   0   0   0   0 0.0   0.0   0.0
Was it helpful?

Solution

I know reshape or melt is probably the "right" way to do it, but with your data it's easy enough to fake it because the columns are sequential.

require(zoo)
stn2 <- stn[,-1]                    # Extracts everything but the Year column
stn2 <- as.vector(t(stn2))          # Turns your matrix into one long vector
date <- apply(                      # Make a date column with a character vector.
             cbind(
                   rep( stn$Year,each=12 ),
                   rep( 1:12, times=length(stn$Year) )
             ), 1, paste, collapse="-" )
date <- as.yearmon(date, "%Y-%m")                # Convert it to a yearmon object
stn2 <- data.frame("Date" = date, "Rain" = stn2) # Make a data frame

OTHER TIPS

You could try using a combination of stn2 <- reshape2::melt(stn, id.vars = Year) and then use this resultmerge(stn2,masteryearlist,all=TRUE) where masteryearlist is something you can manually create.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top