I'm having trouble trying to get an if else statement to work. Essentially, what I want it to do is as follows: if my object (z) exists then append to my data frame (results <- data.frame(x, y, z)), else do nothing (thus results <- data.frame(x, y)).
Below is a reproducible example of what I'm trying to accomplish:
Reproducible example
library(forecast)
set.seed(1234)
testData <- rnorm(1000)
mFits <- function(data, mod1, mod2 = NULL, mod3 = NULL) {
# Must at least choose one model to evaluate
# If mod2, mod3 are specified in the arguments then evaluate
m1 <- mod1(data)$fitted
if (!is.null(mod2)) {
m2 <- mod2(data)$fitted
}
if (!is.null(mod3)){
m3 <- mod3(data)$fitted
}
# Put fitted values into a data frame
if (!is.ts(m2)) {
fits <- data.frame(m1)
}
else {
fits <- data.frame(m1, m2)
}
if (!is.ts(m3)) {
fits <- data.frame(m1)
}
else {
fits <- data.frame(m1, m3)
}
}
modelFit <- mFits(testData, mod1 = auto.arima, mod2 = NULL, mod3 = NULL)
Error in is.ts(m3) : object 'm3' not found
However, I keep getting an error, like the one above. I know m3 does not exists because I did not specify it to exist. Essentially, what I want is a data frame that must have the fitted values from m1, and optionally have the fitted values from m2 and m3 appended if they are specified in the arguments of the function. Could someone point me in the right direction? I'm a bit unsure of what to do next.
Thanks
Aucun commentaire:
Enregistrer un commentaire