2017-09-13 108 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)