【问题标题】:Unexpected output from rollapply due to zero length output from the function由于函数的零长度输出,rollapply 的意外输出
【发布时间】:2014-10-06 03:42:36
【问题描述】:

我遇到了一个我无法理解的问题。这是注释代码:

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 的第一个滚动应该会产生模式矩阵p 中不存在的向量1 -1 1。我期待的是结果NA 1rollapply 一定有一些我不明白的地方,但奇怪的是,如果我将向量 c(-1, -1, -1 ,-1) 提供给 rollapply,我会得到预期的结果 NA NA。在某些情况下,我混合了1 2,但从来没有混合过NA 1NA 2

【问题讨论】:

  • 你能把问题的标题写得更丰富一些吗?类似于“期望 1 -1 1 但从 rollapply 获得 1 1”。
  • 我猜测rollapply 不“喜欢”零长度的输出(即integer(0))并且正在回填该值。
  • 是的,rollapply 不支持产生零长度输出的函数。

标签: r zoo rollapply


【解决方案1】:

根据 G. Grothendieck,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))
  }

【讨论】:

  • 仅供参考 - @G.Grothendieck 是 zoo 的作者,所以他的答案是明确的。
【解决方案2】:

为了完整起见,引用 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 的填充操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2016-04-03
    相关资源
    最近更新 更多