【发布时间】:2016-02-07 07:45:38
【问题描述】:
样本数据
df <- data.frame(id=c("A","A","A","A","B","B","B","B"),year=c(2014,2014,2015,2015),month=c(1,2),marketcap=c(4,6,2,6,23,2,5,34),return=c(NA,0.23,0.2,0.1,0.4,0.9,NA,0.6))
df1
id year month marketcap return
1: A 2014 1 4 NA
2: A 2014 2 6 0.23
3: A 2015 1 2 0.20
4: A 2015 2 6 0.10
5: B 2014 1 23 0.40
6: B 2014 2 2 0.90
7: B 2015 1 5 NA
8: B 2015 2 34 0.60
所需数据
desired_df <- data.frame(id=c("A","A","A","A","B","B","B","B"),year=c(2014,2014,2015,2015),month=c(1,2),marketcap=c(4,6,2,6,23,2,5,34),return=c(0.23,0.23,0.2,0.1,0.4,0.9,0.75,0.6))
desired_df
id year month marketcap return
1 A 2014 1 4 0.23
2 A 2014 2 6 0.23
3 A 2015 1 2 0.20
4 A 2015 2 6 0.10
5 B 2014 1 23 0.40
6 B 2014 2 2 0.90
7 B 2015 1 5 0.75
8 B 2015 2 34 0.60
我想通过 id 将 NA 值替换为时间序列中的相邻值来插入返回值。假设只有两个月:一年有 1,2 个月。
(B,2015,1) 的第二个NA 替换为 0.75 =(0.9+0.6)/2
(A,2014,1) 的第一个 NA 被 0.23 替换,因为没有以前的数据。
如果可能,首选 data.table 解决方案
更新: 当使用如下代码结构时(适用于示例)
df[,returnInterpolate:=na.approx(return,rule=2), by=id]
我遇到了错误: 近似错误(x[!na], y[!na], xout, ...) : 至少需要两个非 NA 值进行插值
我猜可能有一些 id 没有要插入的非 NA 值。 。有什么建议?
【问题讨论】:
-
library(zoo); help("na.approx") -
亲爱的 Roland,如何用 by 进行 na.approx?我想通过 id 进行插值。顺便说一句,我刚刚编辑了问题,我也在寻找 data.table 解决方案以了解更多语法
-
在 approx(x[!na], y[!na], xout, ...) 中出现错误:需要至少两个非 NA 值进行插值 --- 这意味着少于您要应用该方法的系列中的两个非 NA 值 - 然后插值将不起作用
标签: r data.table interpolation na missing-data