[R] missed values

Joshua Ulrich josh.m.ulrich at gmail.com
Sun Dec 2 19:16:46 CET 2012


It's simpler, easier, and more correct to use zoo::na.approx.

R> library(zoo)
R> dat1<-read.table(text=
+ "   date     value
+ 80  2006-10 0.1577647
+ 81  2006-11       NaN
+ 82  2006-12       NaN
+ 83  2007-01       NaN
+ 84  2007-02       NaN
+ 85  2007-03 0.2956429",
+ header=TRUE,stringsAsFactors=FALSE)
R> dat1$valnew <- na.approx(dat1$value, as.yearmon(dat1$date))
R> dat1
      date     value    valnew
80 2006-10 0.1577647 0.1577647
81 2006-11       NaN 0.1853403
82 2006-12       NaN 0.2129160
83 2007-01       NaN 0.2404916
84 2007-02       NaN 0.2680673
85 2007-03 0.2956429 0.2956429

Best,
--
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com


On Fri, Nov 30, 2012 at 11:28 AM, arun <smartpink111 at yahoo.com> wrote:
> Hi,
> May be this helps:
> dat1<-read.table(text="
> -------------------data---
> ",header=TRUE,stringsAsFactors=FALSE)
>
> library(zoo)
>  dat1$date<-as.yearmon(dat1$date,format="%Y-%m")
> lm1<-lm(value~date,dat1)
> dat2<-data.frame(date=dat1[,1])
>  dat1$fit<-predict(lm1,newdata=dat2)
>  dat1<-within(dat1,{newvalue<-ifelse(is.na(value)==T,fit,value)})
> dat1new<-dat1[,c(1:2,4)]
> dat1new[80:86,]
> #       date     value  newvalue
> #80 Oct 2006 0.1577647 0.1577647
> #81 Nov 2006       NaN 0.2782320
> #82 Dec 2006       NaN 0.2773986
> #83 Jan 2007       NaN 0.2765651
> #84 Feb 2007       NaN 0.2757317
> #85 Mar 2007 0.2956429 0.2956429
> #86 Apr 2007 0.3767500 0.3767500
> A.K.
>
>
>
>
> ----- Original Message -----
> From: Vasilchenko Aleksander <vasilchenko.a.p at gmail.com>
> To: arun <smartpink111 at yahoo.com>
> Cc:
> Sent: Friday, November 30, 2012 8:22 AM
> Subject: Re: [R] missed values
>
>    date     value
<snip>
> 80  2006-10 0.1577647
> 81  2006-11       NaN
> 82  2006-12       NaN
> 83  2007-01       NaN
> 84  2007-02       NaN
> 85  2007-03 0.2956429
<snip>
>
> I want to obtain these values by linear interpolation between 80
> 2006-10 0.1577647 and  85  2007-03 0.2956429
> 81  2006-11       NaN
> 82  2006-12       NaN
> 83  2007-01       NaN
> 84  2007-02       NaN
>
> This time series has only one such block, but there can be several
> such blocks in general
>
> thanks
>
>
> ______________________________________________
> 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