HoltWinters 函数单独与 purrr:map 一起使用时工作正常,但在 ifelse 函数中使用时无效

HoltWinters function works fine when used by itself with purrr:map but not when used in an ifelse function

我正在尝试沿矢量迭代地使用 HoltWinters 预测,而不使用循环,但不想在前两个上使用 HoltWinters 函数。我使用 accumulate:

创建了一个向量列表
library(purrr)

v <- c(73,77,71,73,86,87,90)
cumv <- accumulate(v,c)

cumv 中使用 map

# Omit first two 
hw1 <- map(cumv[-c(1:2)], function(x) HoltWinters(ts(x),gamma=F,alpha=0.35,beta=0.2))

> hw1[[5]]

#Holt-Winters exponential smoothing with trend and without seasonal component.

#Call:
#HoltWinters(x = ts(x), alpha = 0.35, beta = 0.2, gamma = F)

#Smoothing parameters:
# alpha: 0.35
# beta : 0.2
# gamma: FALSE

#Coefficients:
#       [,1]
#a 89.605082
#b  3.246215

这个 给出了我想要的结果,但不包括前两次迭代。我假设使用 ifelse 会很好:

# Include first two, use ifelse
hw2 <- map(cumv, function(x) ifelse(length(x)>2,HoltWinters(ts(x),gamma=F,alpha=0.35,beta=0.2),
                                    ifelse(length(x)>1,max(x),NA)))

现在,hw2[[7]] 应该(我认为)返回一个相同的对象给 hw1[[5]] 但它没有。

> hw2[[7]]

#[[1]]
#Time Series:
#Start = 3 
#End = 7 
#Frequency = 1 
#      xhat    level    trend
#3 81.00000 77.00000 4.000000
#4 80.80000 77.50000 3.300000
#5 80.82400 78.07000 2.754000
#6 85.75192 82.63560 3.116320
#7 89.39243 86.18875 3.203686

为什么会乱码?

正如 Dason 在他们的评论中提到的,ifelse() 函数与使用 if else 语句不同。前者 returns x 的每个元素的单个值,假设 x 是包含布尔值的向量,例如

x <- c(TRUE, TRUE, FALSE, FALSE)
ifelse (x, "A", "B")

returns [1] "A" "A" "B" "B"

为了您的目的,您想使用正常的 if else 构造:

hw2 <- map(cumv, function(x) {
    if (length(x) > 2) {
        return (HoltWinters(ts(x),gamma=F,alpha=0.35,beta=0.2))
    } else if (length(x) > 1) {
        return (max(x))
    } else {
        return (NA)
    }
})