2017-10-06 119 views
0

我正在寻找一种方法来计算像here但根据特定的观察(移动计数)来改变标准的能力的观察。计数观测

例如 - (从最后的50)计数的MAG的观测数其比MAG的特定观察更大。 代码我有:

rollapplyr(zoo(mag),50,function(i){sum(mag>i)},partial=T,by.column=F,fill=NA)) 

此代码取50个最后观测的平均MAG和计算高于平均观测值的数目(在整个数据集)。

我错过了什么? 也许使用rollapply不是这种情况? 总结:
1.根据特定行值计数
2.仅在50个最后的观察值(而不是整个数据列)中进行计数。

+0

第一个问题是'i'在你的函数是 “窗口” 数据和'mag',如你说,在整个专栏。所以代码绝对不是你上面说的。此外,没有样本数据和预期的输出,如果可以的话,请添加它。 –

回答

2

请参阅 “校正” 的功能:

set.seed(2017) 
mag <- sample(x = 1000, size = 20) 

## Your function, see what is printed 
# my_fun <- function(i) { 
# print(i) 
# print(mag) 
# sum(mag > i) 
# } 

## Corrected one 
my_fun <- function(i) { 
    print(i) 
    print(tail(i, 1)) 
    sum(i > tail(i, 1)) 
} 

# debug(my_fun) # Play a little with debug(), it is worth it! 

mag_out <- zoo::rollapplyr(
    # zoo::zoo(mag), 
    mag, 
    5, 
    my_fun, 
    partial = TRUE, 
    by.column = FALSE, 
    fill = NA 
) 

rbind(
    mag, 
    mag_out 
) 

输出:

 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] 
mag  244 329 987 833 524 112 869 327 488 691 89 224 206 73 803 868 288 365 666 145 
mag_out 0 0 0 1 2 4 1 3 2  1  4  3  3  4  0  0  2  2  2  4 
+1

非常感谢m-dz! 我没有太多的R经验 - 我会尝试学习如何根据您的建议进行调试。 –