R 根据平均变化百分比推断各组缺失数据
我有一个数据框,包含2010-2014年按邮政编码划分的平均收入。我需要2015-2017年的数据,因此我正在寻找一种方法,根据可用年份每个邮政编码组的年平均变化来推断这一点 例如:R 根据平均变化百分比推断各组缺失数据,r,percentage,extrapolation,R,Percentage,Extrapolation,我有一个数据框,包含2010-2014年按邮政编码划分的平均收入。我需要2015-2017年的数据,因此我正在寻找一种方法,根据可用年份每个邮政编码组的年平均变化来推断这一点 例如: year zip income 2010 1111 5000 2011 1111 5500 2012 1111 6000 2013 1111 6500 2014 1111 7000 2010 2222 5000 2011 2222 6000 2012 2222
year zip income
2010 1111 5000
2011 1111 5500
2012 1111 6000
2013 1111 6500
2014 1111 7000
2010 2222 5000
2011 2222 6000
2012 2222 7000
2013 2222 8000
2014 2222 9000
应(大致)具备:
基于邮政编码1111的平均增长率为8.78%,邮政编码2222的平均增长率为15.83%。这里有一个非常快速的混乱数据。表的想法
library(data.table)
#Create data
last_year <- 2014
dt <- data.table(year=rep(2010:last_year,2),
zip=c(rep(1111,5),rep(2222,5)),
income=c(seq(5000,7000,500),seq(5000,9000,1000)))
#Future data
dt_fut <- data.table(year=rep((last_year+1):2017,2),
zip=c(rep(1111,3),rep(2222,3)),
income=rep(NA_integer_,6))
#calculate mean percentage change per year
dt[,avg_growth:=mean(diff(log(income))),by=zip]
#bind old with future data
dt <- rbindlist(list(dt,dt_fut),fill=T);setorder(dt,zip,year)
#carry last value forward replace NA
dt[,avg_growth:=na.locf(avg_growth),by=zip][,income:=na.locf(income),by=zip]
#calculate
# after 2014+1 (2015) then replace income
# with income*cumulative product of the average growth (1+r)-1
dt[year>=last_year+1,income:=income*cumprod(1+avg_growth)-1,by=zip][]
库(data.table)
#创建数据
去年用method=“linear”
尝试?approx
。虽然我不知道这个函数,但这并没有让我走多远,因为我无法在数据框中创建新的年份,并根据组进行插值。听到这个消息,我很难过。
library(data.table)
#Create data
last_year <- 2014
dt <- data.table(year=rep(2010:last_year,2),
zip=c(rep(1111,5),rep(2222,5)),
income=c(seq(5000,7000,500),seq(5000,9000,1000)))
#Future data
dt_fut <- data.table(year=rep((last_year+1):2017,2),
zip=c(rep(1111,3),rep(2222,3)),
income=rep(NA_integer_,6))
#calculate mean percentage change per year
dt[,avg_growth:=mean(diff(log(income))),by=zip]
#bind old with future data
dt <- rbindlist(list(dt,dt_fut),fill=T);setorder(dt,zip,year)
#carry last value forward replace NA
dt[,avg_growth:=na.locf(avg_growth),by=zip][,income:=na.locf(income),by=zip]
#calculate
# after 2014+1 (2015) then replace income
# with income*cumulative product of the average growth (1+r)-1
dt[year>=last_year+1,income:=income*cumprod(1+avg_growth)-1,by=zip][]