使用均匀增长的中间值桥接上一个和下一个非NA值

时间:2018-05-20 21:35:30

标签: r data.table na locf

在数据帧列中填充缺失的NA的好方法是什么,中间值从最后一个非NA值逐渐增长到下一个非NA值?

以下是一个示例:对于列成本,我想获得列成本_esti,其中2014年至2016年间每年成本增加31美元,将最后已知成本595美元与下一个已知成本720美元相连

enter image description here

我提出的代码很冗长。是否有一种优雅的方式来做同样的事情?

library(data.table)
data = data.table(year=2000:2018,
                  cost = c(100,120,NA,200,220,NA,NA,300,350,470,500,NA,NA,595,NA,NA,NA,720,800))

data[,cost_nas:=as.numeric(is.na(cost))]

## consecutive nas so far for each row:
data[, consecutive_nas_so_far := seq_len(.N), by=rleid(cost_nas)]
data[cost_nas==0,consecutive_nas_so_far:=0]

# total number of consecutive nas in the sequence
data[,total_number_of_consec_nas:=ifelse(consecutive_nas_so_far>0&shift(consecutive_nas_so_far,1,type = "lead")==0,consecutive_nas_so_far,NA)]
data[cost_nas==0,total_number_of_consec_nas:=0]
data[,total_number_of_consec_nas:=zoo::na.locf(total_number_of_consec_nas,fromLast=T)]

#get last and next known values for cost:
data[,cost_previous:=zoo::na.locf(cost)]
data[,cost_following:=zoo::na.locf(cost,fromLast=T)]

# apply the formula to calculate the gradual increase from cost_previous to cost_following
data[,cost_esti:=round(consecutive_nas_so_far*(cost_following-cost_previous)/(total_number_of_consec_nas+1)+cost_previous,0)]
data[is.na(cost_esti),cost_esti:=cost]

2 个答案:

答案 0 :(得分:1)

您可以使用re-writezoo::na.locf进行data.table::rleid data.table操作。使用lastNonNA添加2列,nextNonNAna.locf各一列。 rleid会为您提供连续NA的独特群组。现在,您可以在NAlinear之间使用lastNonNA编写逻辑以填充nextNonNA

library(data.table)
library(zoo)
#Data
data = data.table(year=2000:2018,
       cost = c(100,120,NA,200,220,NA,NA,300,350,470,500,NA,NA,595,NA,NA,NA,720,800))

data[,':='(lastNonNA = na.locf(cost, fromLast = FALSE), 
nextNonNA = na.locf(cost, fromLast = TRUE), Group_NA = rleid(is.na(cost)))][
  ,':='(IDX = 1:.N), by=Group_NA][
  ,':='(cost = ifelse(is.na(cost), lastNonNA + IDX*((nextNonNA - lastNonNA)/(.N+1)),cost)), 
    by=Group_NA][,.(year, cost)]

#    year     cost
# 1: 2000 100.0000
# 2: 2001 120.0000
# 3: 2002 160.0000   #Filled
# 4: 2003 200.0000
# 5: 2004 220.0000
# 6: 2005 246.6667  #Filled 
# 7: 2006 273.3333  #Filled
# 8: 2007 300.0000
# 9: 2008 350.0000
# 10: 2009 470.0000
# 11: 2010 500.0000
# 12: 2011 531.6667 #Filled
# 13: 2012 563.3333 #Filled
# 14: 2013 595.0000
# 15: 2014 626.2500 #Filled 
# 16: 2015 657.5000 #Filled
# 17: 2016 688.7500 #Filled
# 18: 2017 720.0000
# 19: 2018 800.0000

答案 1 :(得分:0)

您要的问题是线性插值。 对于使用NA的数据,可以很容易地在R中获得它。

在这种情况下,解决方案是:

library("imputeTS")
na_interpolation(data, option = "linear")

您还可以使用option =“ spline”或“ stine”,则增加不一定严格线性。