2014-10-06 30 views
2

我遇到了一个令我难以理解的问题。这里是注释掉的代码:由于函数零长度输出导致的意外输出

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 1NA 2

+0

您能否让问题标题更具信息性?沿着“期望1 -1 1但是从rollapply获得1 1”的方向行事。 – 2014-10-06 07:21:21

+0

我疯狂地猜测'rollapply'不会“类似”零长度的输出(即'integer(0)')并且正在回填该值。 – 2014-10-06 12:08:58

+2

是的,'rollapply'不支持产生零长度输出的函数。 – 2014-10-06 13:27:34

回答

3

根据G.Gotothendieck rollapply不支持产生零长度输出的函数。通过在函数f中添加一个条件来返回特定的输出,以防万一它返回零长度输出时,可以摆脱该问题。

f <- function(x) { # identifies which row of `patterns` matches sign(x) 
    t <- which(apply(patterns,1,function(row)all(row==sign(x)))) 
    ifelse(length(t)==0, return(0), return(t)) 
    } 
+0

仅供参考 - @ G.Grothendieck是“动物园”的作者,所以他是一个明确的答案。 – jlhoward 2014-10-06 13:40:50

+0

好的,我相应编辑。 – Wicelo 2014-10-06 14:25:54

0

为了完整起见,引用了GGrothendieck的评论。 “rollapply不支持产生零长度输出的函数”。这与下面的行为是一致的。

而且混乱,至少对我来说(这应该是一个评论,但我想一些体面的格式):

sfoo<-c(1,-1,1,1,1,-1,1,1) rollapply(sfoo,width=3,function(j){k<-f(j);print(j);return(k)}) [1] 1 -1 1 [1] -1 1 1 [1] 1 1 1 [1] 1 1 -1 [1] 1 -1 1 [1] -1 1 1 [1] 1 2 1 1 2 1

然后我尝试:

ff<-function(x) which(rowSums(p)==sum(x)) 
sbar<-c(0,1,1,1,-1,0,-1) 
rollapply(sbar,width=3,function(j){k<-ff(j);print(j);return(k)}) 
[1] 0 1 1 
[1] 1 1 1 
[1] 1 1 -1 
[1] 1 -1 0 
[1] -1 0 -1 
[1] 2 1 2 1 2 

这看起来确实像rollapply正在做一个na.locf - 灌装操作的种类。