我遇到了一个我很难理解的问题。这是注释代码:
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
。
答案 0 :(得分:3)
根据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))
}
答案 1 :(得分: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
- 正在填写操作。