Reputation: 2949
I have time-series (xts
formatted) power consumption data at 10 minutes rate as
power
2015-08-01 00:00:00 101.22
2015-08-01 00:10:00 122.941
2015-08-01 00:20:00 67.596
2015-08-01 00:30:00 184.180
Now I want to add 3 more columns to it as:
Somehow new xts
object will be like
power prevday1 prevday2 previnstant1
2015-08-01 00:00:00 101.22 NA NA NA
2015-08-01 00:10:00 122.941 : : :
2015-08-01 00:20:00 67.596
2015-08-01 00:30:00 184.180
:
Now the question is how should I extract the values for columns 2, 3 and 4 from the historical xts
object. I started with .indexday
type of functions but could not get the values. Is there any specific function in R
to extract these type of values using xts
indexes?
Upvotes: 1
Views: 1262
Reputation: 2949
After struggling for a complete day, I came out with a way to fill the remaining three columns. The approach is:
Code is:
#x is a xts time series object containing columns as shown in question
dates <- as.Date(index(x),tz="Asia/Kolkata") # timestamp in date format
for(i in 0:200) # no. of observations
{
a <- x[i,1] # Current observation
prev_d1 <- as.Date(index(a), tz ="Asia/Kolkata")-1 # previous day
prev_d2 <- as.Date(index(a), tz ="Asia/Kolkata")-2 # previous to previous day
prev_value1 <- x[dates %in% prev_d1 & .indexhour(x) %in% .indexhour(a) & .indexmin(x) %in% .indexmin(a)]$power
prev_value2 <- x[dates %in% prev_d2 & .indexhour(x) %in% .indexhour(a) & .indexmin(x) %in% .indexmin(a)]$power
x[i,"prevday1"] <- if(length(prev_value1)!=0) prev_value1 else NA
x[i,"prevday2"] <- if(length(prev_value2)!=0) prev_value2 else NA
x[i,"previnstant1"] <- ifelse(length(x[index(a)-frequency]$power)!=0, x[index(a)-frequency]$power, NA)# frequency represents periodicity values in terms of seconds
}
Upvotes: 0