Beta Beta - 2 months ago 11
R Question

Extend Date in my Dataframe

My data looks like the following

Date Value
2/11/2016 20.0
2/18/2016 21.0
2/25/2016 18.3
3/4/2016 19.1
3/11/2016 26.3
3/18/2016 21.1
NA 26.2
NA 18.6
NA 17.9


I want to add date in place of "NA". SO the new data looks like

Date Value
2/11/2016 20.0
2/18/2016 21.0
2/25/2016 18.3
3/4/2016 19.1
3/11/2016 26.3
3/18/2016 21.1
3/25/2016 26.2
1/4/2016 18.6
8/4/2016 17.9


Note that addition of date is 7 increment of the previous date. Can anyone please help me how to extend the date?

Thank you!

Answer

Like most software, R stores dates as numeric values under the hood. Assuming this is a one-off problem and your data are stored as numeric, you could do it with a little for loop. If they're currently character variables, coerce to date using as.Date() first.

for(i in 7:9){
  df$Date[i] <- df$Date[i-1]+7
}

Though I'm sure there are other wizards here who have a vectorized solution....

Comments