[R] insert missing dates

Rui Barradas ruipbarradas at sapo.pt
Tue Jul 3 18:04:30 CEST 2012


Hello,

The trick is to use seq() for date classes.
First of all, when creating data.frames use stringsAsFactors=FALSE, in 
order not to convert them to factors. I've added this option to your 
data.frame() instructions. And then,


mydata1$dates  <- as.POSIXct(mydata1$dates)
mydata1b$dates <- as.POSIXct(mydata1b$dates)
mydata2$dates  <- as.POSIXct(mydata2$dates)
mydata2b$dates <- as.POSIXct(mydata2b$dates)


Now, first we create the sequences then use merge(9, that will take care 
of inserting the NAs.

# mydata1
tmp <- tapply(mydata1$dates, format(mydata1$dates, "%Y-%m-%d"), function(x){
		if(length(x) < 2) paste(format(x, "%Y-%m-%d"), c("07:00:00", "19:00:00"))
		else sub("0 [[:alpha:]]+$", "", x)
	})
tmp <- as.POSIXct(unlist(tmp))
merge(mydata1, data.frame(dates=tmp), all.y=TRUE)

# and mydata2
tmp <- data.frame(dates=seq(mydata2$dates[1], mydata2$dates[n], by="10 
mins"))
merge(mydata2, tmp, all.y=TRUE)


Hope this helps,

Rui Barradas

Em 03-07-2012 10:52, Васильченко Александр escreveu:
> Hello
> I have dataframes.
> mydata1 <-data.frame(value=c(15,20,25,30,45,50),dates=c("2005-05-25 07:00:00
> ","2005-05-25 19:00:00","2005-06-25 07:00:00","2005-06-25 19:00:00
> ","2005-07-25 07:00:00","2005-8-25 19:00:00"))
> or
> mydata2 <-data.frame(value=c(15,20,25,30,45,50),dates=c("2005-05-25 00:00:00
> ","2005-05-25 00:10:00","2005-05-25 00:30:00","2005-05-25 00:40:00
> ","2005-05-25 00:50:00","2005-5-25 01:10:00"))
>
> I have to get  such dataframes
>
> mydata1 <-data.frame(value=c(15,20,25,30,45,NA,NA,50),dates=c("2005-05-25
> 07:00:00","2005-05-25 19:00:00","2005-06-25 07:00:00","2005-06-25 19:00:00
> ","2005-07-25 07:00:00","2005-07-25 19:00:00","2005-8-25 07:00:00",
> "2005-8-25 19:00:00"))
> or
> mydata2 <-data.frame(value=c(15,20,NA,25,30,45,NA,50),dates=c("2005-05-25
> 00:00:00","2005-05-25 00:10:00","2005-05-25 00:20:00","2005-05-25 00:30:00
> ","2005-05-25 00:40:00","2005-05-25 00:50:00","2005-5-25 01:00:00",
> "2005-5-25 01:10:00"))
>
> Regards, Aleksander.
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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