[R] Filling in Gapped Interval of a Data Frame As Series
Gabor Grothendieck
ggrothendieck at gmail.com
Sun Apr 5 12:10:11 CEST 2009
Try this:
> library(zoo)
> Lines <- "-8 100
+ -6 20.2
+ -1 1.5
+ 2 3.00
+ 3 78.8
+ 5 33.2
+ 6 44.5
+ 7 5.00"
> DF <- read.table(textConnection(Lines))
> z <- zoo(DF$V2, DF$V1)
> zz <- merge(z, zoo(, seq(min(time(z)), max(time(z)))), fill = 0); zz
-8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4
100.0 0.0 20.2 0.0 0.0 0.0 0.0 1.5 0.0 0.0 3.0 78.8 0.0
5 6 7
33.2 44.5 5.0
If you want to create a data frame from that try this:
newDF <- data.frame(Time = time(zz), Value = coredata(zz))
although you might be best off to just leave it as a zoo object
so that you can make use of other zoo methods too.
> plot(zz, type = "o")
See the three zoo vignettes (PDF documents) for more info.
On Sun, Apr 5, 2009 at 3:22 AM, Gundala Viswanath <gundalav at gmail.com> wrote:
> Dear all,
>
> I have a data frame that looks like this:
>
>> dat
> V1 V2
> 1 -8 100
> 2 -6 20.2
> 3 -1 1.5
> 4 2 3.00
> 5 3 78.8
> 6 5 33.2
> 7 6 44.5
> 8 7 5.00
>
> Now I want to fill the V1 column in series (note that it is gapped),
> with the corresponding value in V2 as 0.
>
> So in the end we would like to have:
>
>> newdat
> V1 V2
> 1 -8 100
> 2 -6 20.2
> 3 -7 0
> 4 -6 0
> 5 -5 0
> 6 -4 0
> 7 -3 0
> 8 -2 0
> 9 -1 1.5
> 10 0 0
> 11 1 0
> 12 2 3.00
> 13 3 78.8
> 14 4 0
> 15 5 33.2
> 16 6 44.5
> 17 7 5.00
>
> Is there a way to do it in R?
> - Gundala Viswanath
> Jakarta - Indonesia
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list