我遇到了一个令我难以理解的问题。这里是注释掉的代码:由于函数零长度输出导致的意外输出
library(zoo)
#Pattern p used as row feeding matrix to apply() for function f
> p
[,1] [,2] [,3]
[1,] -1 1 1
[2,] 1 1 1
#Function f supposed to take rows of matrix p as vectors,
#compare them with vector x and return index
f <- function(x) { # identifies which row of `patterns` matches sign(x)
which(apply(p,1,function(row)all(row==sign(x))))
}
#rollapplying f over c(1,-1,1,1) : there is no vector c(1,-1,1) in p
#so why the first atom is 1 ?
> rollapply(c(1,-1,1,1),width=3,f,align="left")
[1] 1 1
#rollapply identity, rollapply is supposed to feed row to the function right ?
> t = rollapply(c(1,-1,1,1),width=3,function(x)x,align="left")
[,1] [,2] [,3]
[1,] 1 -1 1
[2,] -1 1 1
#Feeding the first row of the precedent matrix to f is giving the expected result
> f(t[1,])
integer(0)
#rollapply feeds the rolls to the function
> rollapply(c(1,-1,1,1),width=3,function(x) paste(x,collapse=","),align="left")
[1] "1,-1,1" "-1,1,1"
#rollapply feeds vectors to the function
> rollapply(c(1,-1,1,1),width=3,function(x) is.vector(x),align="left")
[1] TRUE TRUE
#Unconsistent with the 2 precedent results
> f(c(1,-1,1))
integer(0)
基本上,我不明白为什么rollapply(c(1,-1,1,1),width=3,f,align="left")
将返回1 1
当从rollapply
第一卷应该产生矢量1 -1 1
是从模式矩阵p
缺席。我期待的结果是NA 1
。必须有一些我不明白的rollapply
,但奇怪的是,如果我将矢量c(-1, -1, -1 ,-1)
加载到rollapply
我得到预期结果NA NA
。在某些情况下,我有一个混合1 2
,但从来没有混合NA 1
或NA 2
。
您能否让问题标题更具信息性?沿着“期望1 -1 1但是从rollapply获得1 1”的方向行事。 – 2014-10-06 07:21:21
我疯狂地猜测'rollapply'不会“类似”零长度的输出(即'integer(0)')并且正在回填该值。 – 2014-10-06 12:08:58
是的,'rollapply'不支持产生零长度输出的函数。 – 2014-10-06 13:27:34