gpt4 book ai didi

r - 趋势长度 - 面板数据

转载 作者:行者123 更新时间:2023-12-02 07:03:16 25 4
gpt4 key购买 nike

我有一个平衡良好的面板数据集,其中包含 NA 观测值。我将使用 LOCF,并想知道每个面板中有多少个连续的 NA,然后再进行观察。 LOCF 是一个过程,其中可以使用“最后的观察结转”来“填充”缺失值。这在一些时间序列应用程序中是有意义的;也许我们有 5 分钟增量的天气数据:对缺失观测值的一个很好的猜测可能是 5 分钟前的观测。

显然,在一个小组中将观察结果提前一小时比在同一小组中将相同的观察结果提前到下一年更有意义。

我知道您可以使用 zoo::na.locf 设置“maxgap”参数,但是,我想更好地了解我的数据。请看一个简单的例子:

require(data.table)
set.seed(12345)

### Create a "panel" data set
data <- data.table(id = rep(1:10, each = 10),
date = seq(as.POSIXct('2012-01-01'),
as.POSIXct('2012-01-10'),
by = '1 day'),
x = runif(100))

### Randomly assign NA's to our "x" variable
na <- sample(1:100, size = 52)
data[na, x := NA]

### Calculate the max number of consecutive NA's by group...this is what I want:
### ID Consecutive NA's
# 1 1
# 2 3
# 3 3
# 4 3
# 5 4
# 6 5
# ...
# 10 2

### Count the total number of NA's by group...this is as far as I get:
data[is.na(x), .N, by = id]

欢迎所有解决方案,但高度推荐 data.table 解决方案;数据文件很大。

最佳答案

这样做就可以了:

data[, max(with(rle(is.na(x)), lengths[values])), by = id]

我只是运行 rle 来查找所有连续的 NA 并选择最大长度。


对于恢复上述 max 的日期范围的评论问题,这是一个相当复杂的答案:

data[, {
tmp = rle(is.na(x));
tmp$lengths[!tmp$values] = 0; # modify rle result to ignore non-NA's
n = which.max(tmp$lengths); # find the index in rle of longest NA sequence

tmp = rle(is.na(x)); # let's get back to the unmodified rle
start = sum(tmp$lengths[0:(n-1)]) + 1; # and find the start and end indices
end = sum(tmp$lengths[1:n]);

list(date[start], date[end], max(tmp$lengths[tmp$values]))
}, by = id]

关于r - 趋势长度 - 面板数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16820072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com