Combining vectors of unequal length into a data frame

前端 未结 3 1809
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 06:04

I have a list of vectors which are time series of inequal length. My ultimate goal is to plot the time series in a ggplot2 graph. I guess I am better off first

3条回答
  •  感动是毒
    2020-12-06 06:37

    I think that you may be approaching this the wrong way:

    If you have time series of unequal length then the absolute best thing to do is to keep them as time series and merge them. Most time series packages allow this. So you will end up with a multi-variate time series and each value will be properly associated with the same date.

    So put your time series into zoo objects, merge them, then use my qplot.zoo function to plot them. That will deal with switching from zoo into a long data frame.

    Here's an example:

    > z1 <- zoo(1:8, 1:8)
    > z2 <- zoo(2:8, 2:8)
    > z3 <- zoo(4:8, 4:8)
    > nm <- list("z1", "z2", "z3")
    > z <- zoo()
    > for(i in 1:length(nm)) z <- merge(z, get(nm[[i]]))
    > names(z) <- unlist(nm)
    > z
      z1 z2 z3
    1  1 NA NA
    2  2  2 NA
    3  3  3 NA
    4  4  4  4
    5  5  5  5
    6  6  6  6
    7  7  7  7
    8  8  8  8
    > 
    > x.df <- data.frame(dates=index(x), coredata(x))
    > x.df <- melt(x.df, id="dates", variable="val")
    > ggplot(na.omit(x.df), aes(x=dates, y=value, group=val, colour=val)) + geom_line() + opts(legend.position = "none")
    

提交回复
热议问题