【发布时间】: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 1。 rollapply 一定有一些我不明白的地方,但奇怪的是,如果我将向量 c(-1, -1, -1 ,-1) 提供给 rollapply,我会得到预期的结果 NA NA。在某些情况下,我混合了1 2,但从来没有混合过NA 1 或NA 2。
【问题讨论】:
-
你能把问题的标题写得更丰富一些吗?类似于“期望 1 -1 1 但从 rollapply 获得 1 1”。
-
我猜测
rollapply不“喜欢”零长度的输出(即integer(0))并且正在回填该值。 -
是的,
rollapply不支持产生零长度输出的函数。