2017-09-13 107 views
4

假设我有一个表作为这样:的R - 估计缺失值

Date  Sales 
09/01/2017 9000 
09/02/2017 12000 
09/03/2017 0 
09/04/2017 11000 
09/05/2017 14400 
09/06/2017 0 
09/07/2017 0 
09/08/2017 21000 
09/09/2017 15000 
09/10/2017 23100 
09/11/2017 0 
09/12/2017 32000 
09/13/2017 8000 

Here is what the data in the table looks like

在表中的值,通过该本人都进不去的R程序估计(这是一个黑色盒子现在)。由于我们的摄取/ ETL过程中存在问题,现在有几天有0个值趋于蠕变。我需要估计0个数据的日期值。

我们的做法是:

  • 绘制从日线之前丢失的数据的日期权 后丢失的数据
  • 估计从线丢失日期值

现在,如果只有一天在两个好日子之间缺少数据,那么直截了当的意思是可行的。如果连续两天或更多的数据缺失,平均值将不起作用,所以我试图制定一种方法来估算多个数据点的值。

The intersection of the green and red lines would give the required values

会在读该方法的工作?我在R的总数n00b,所以我不确定这是否可行。

+0

回答以下的作品,但你也可以完成同样的事情用'zoo'包和'na.spline' – CCurtis

回答

6

您可以使用函数approxfun通过线性插值填充值。

## Your data 
df = read.table(text="Date  Sales 
09/01/2017 9000 
09/02/2017 12000 
09/03/2017 0 
09/04/2017 11000 
09/05/2017 14400 
09/06/2017 0 
09/07/2017 0 
09/08/2017 21000 
09/09/2017 15000 
09/10/2017 23100 
09/11/2017 0 
09/12/2017 32000 
09/13/2017 8000", 
header=TRUE, stringsAsFactors=FALSE) 
df$Date = as.Date(df$Date, format="%m/%d/%Y") 


## Create function for linear interpolation 
Interp = approxfun(df[df$Sales > 0, ]) 

## Use function to fill in interpolated values 
Vals = Interp(df$Date[df$Sales == 0]) 
df$Sales[df$Sales == 0] = Vals 
plot(df, type="l") 
grid() 

Interpolated values

4

我们还可以使用na.interpolation函数从imputeTS包。 na.interpolation的默认方法是线性插值,但如果需要,我们也可以指定其他方法。

library(dplyr) 
library(imputeTS) 

dt2 <- dt %>% 
    replace(. == 0, NA) %>% 
    mutate(Sales = na.interpolation(Sales)) 

dt2 
     Date Sales 
1 09/01/2017 9000 
2 09/02/2017 12000 
3 09/03/2017 11500 
4 09/04/2017 11000 
5 09/05/2017 14400 
6 09/06/2017 16600 
7 09/07/2017 18800 
8 09/08/2017 21000 
9 09/09/2017 15000 
10 09/10/2017 23100 
11 09/11/2017 27550 
12 09/12/2017 32000 
13 09/13/2017 8000 

数据

dt <- read.table(text = "Date  Sales 
09/01/2017 9000 
       09/02/2017 12000 
       09/03/2017 0 
       09/04/2017 11000 
       09/05/2017 14400 
       09/06/2017 0 
       09/07/2017 0 
       09/08/2017 21000 
       09/09/2017 15000 
       09/10/2017 23100 
       09/11/2017 0 
       09/12/2017 32000 
       09/13/2017 8000", 
       header = TRUE, stringsAsFactors = FALSE)