Reputation: 135
Hi I have df as below which value column has NA value how to replace NA values previous values with in last 7 days . if non NA value not found in last 7 days then no replacement for eg: there is no values for 10-01-2016 in last 7 days with that day
Name value new_col
01-01-2016 NA *NA*
02-01-2016 43
03-01-2016 NA *43*
04-01-2016 NA *43*
05-01-2016 NA *43*
06-01-2016 NA *43*
07-01-2016 NA *43*
08-01-2016 NA *43*
09-01-2016 NA *43*
10-01-2016 NA *NA*
11-01-2016 12
12-01-2016 33
13-01-2016 NA *33*
14-01-2016 NA *33*
we can fill with NA previous valu using ZOO lib
df<- transform(df, value = na.locf(value))
df$new_col = ifelse(is.na(df$value) & (df$Name-7), na.locf(df$value), df$value)
Upvotes: 1
Views: 125
Reputation: 1253
You can use na.locf
from zoo
package, with argument maxgap
:
(Note that we assume your data is arranged by date without missing holes in the serie)
library(zoo)
df$new_col <- na.locf(df$value, maxgap = 7, na.rm = FALSE)
Upvotes: 3