Error when plotting HoltWinters graph - r

The following R code is giving me an error when trying to plot the HoltWinters graph as done here:
# init X
X11()
# get data
mydata = read.csv("lookup.csv", header=TRUE, stringsAsFactors=FALSE)
# data post-proc
mydata = as.data.frame(mydata)
mydata$Time = as.POSIXlt(mydata$Time, format='%d.%m.%Y %H:%M:%S')
# create time series - hourly data -> 8765 hours/year
dataTimeSeries <- ts(mydata$Close, frequency=8765)
dataForecasts = HoltWinters(dataTimeSeries, beta=FALSE, gamma=FALSE)
# output
plot.ts(dataForecasts)
message("Press Return To Continue")
invisible(readLines("stdin", n=1))
The error I'm getting is:
$ Rscript simple_forecast.R
Error in xy.coords(x, NULL, log = log) :
(list) object cannot be coerced to type 'double'
Calls: plot.ts -> plotts -> xy.coords
Execution halted
I'm quite perplexed, since print(dataForecasts) prints the correct data. I can also plot dataTimeSeries without a problem.
lookup.csv (pastebin)

Generally one should rely upon R to do the dispatch of class-dependent functions, and do notice that the example you cited at Avril Coghlan's page only used plot, not plot.ts.
(m <- HoltWinters(co2))
plot.ts(m)
Error in xy.coords(x, NULL, log = log) :
(list) object cannot be coerced to type 'double'
plot(m) # success

Related

Error in eval(expr, p): object 'X' not found; predict (BayesARIMAX)

I am trying to use BayesARIMAX to model and predict us gdp (you can find the data here: https://fred.stlouisfed.org/series/GDP).I followed the example (https://cran.r-project.org/web/packages/BayesARIMAX/BayesARIMAX.pdf) to build my model. I didnt have any major issue to build the model(used error handling to overcome Getting chol.default error when using BayesARIMAX in R issue). However could not get the prediction of the model. I tried to look for solution and there is no example of predicting the model that is build using BayesARIMAX. Every time that I run the "predict" I get the following error:
"Error in eval(expr, p) : object 'X' not found"
Here is my code.
library(xts)
library(zoo)
library(tseries)
library(tidyverse)
library(fpp2)
gdp <- read.csv("GDP.csv", head = T)
date.q <- as.Date(gdp[, 1], "%Y-%m-%d")
gdp <- xts(gdp[,2],date.q)
train.row <- 248
number.row <- dim(merge.data)[1]
gdp.train <- gdp[1:train.row]
gdp.test <- gdp[(train.row+1):number.row]
date.test <- date.q[(train.row+1):number.row]
library(BayesARIMAX)
#wrote this function to handle randomly procuded error due to MCMC simulation
test_function <- function(a,b,P=1,Q=1,D=1,error_count = 0)
{
tryCatch(
{
model = BayesARIMAX(Y=a,X = b,p=P,q=Q,d=D)
return(model)
},
error = function(cond)
{
error_count=error_count+1
if (error_count <40)
{
test_function(a,b,P,Q,D,error_count = error_count)
}
else
{
print(paste("Model doesnt converge for ARIMA(",P,D,Q,")"))
print(cond)
}
}
)
}
set.seed(1)
x = rnorm(length(gdp.train),4,1)
bayes_arima_model <- test_function(a = gdp.train,b=x,P = 3,D = 2,Q = 2)
bayes_arima_pred <- xts(predict(bayes_arima_model[[1]],newxreg = x[1:3])$pred,date.test)
and here is the error code
Error in eval(expr, p) : object 'X' not found
Here is how I resolve the issue after reading through the BayesARIMAX code (https://rdrr.io/cran/BayesARIMAX/src/R/BayesianARIMAX.R) . I basically created the variable "X" and passed it to predict function to get the result. You just have to set the length of X variable equal to number of prediction.
here is the solution code for prediction.
X <- c(1:3)
bayes_arima_pred <- xts(predict(bayes_arima_model[[1]],newxreg = X[1:3])$pred,date.test)
which gave me the following results.
bayes_arima_pred
[,1]
2009-01-01 14462.24
2009-04-01 14459.73
2009-07-01 14457.23

tryCatch() does not suppress the error messages

I would like to create a function that does not print any error messages.
Let's say I have the following data:
library(fitdistrplus)
vec <- rnorm(100)
Then the following gives an error message:
fitdist(vec, "exp")
#> Error in computing default starting values.
#> Error in manageparam(start.arg = start, fix.arg = fix.arg, obs = data, : Error in start.arg.default(obs, distname) :
#> values must be positive to fit an exponential distribution
Now I would like to create a function that does return NULL. I tried this with tryCatch(). The problem is that fit_fn() still returns the error 'Error in computing default starting values':
fit_fn <- function(x){
tryCatch(fitdist(x, "exp"), error = function(e){ NULL })
}
fit_fn(vec)
#> Error in computing default starting values.
#> NULL
What is the way to do this? Only NULL should be printed here:
fit_fn(vec)
#> NULL
Created on 2021-11-02 by the reprex package (v2.0.1)
Desipte the fact that it says it's an error, the message that's being displayed is done not via the error mechanism, but the output is being printed directly to the console because it's already in it's own error handler. If you want to suppress that message, you'll need to capture the output of the function. Then you can ignore that output.
You can do that with
fit_fn <- function(x){
capture.output(result <- tryCatch(fitdist(x, "exp"),
error = function(e){ NULL }))
result
}
fit_fn(vec)
# NULL

code can be progress but shown has error when i convert html in r

I would like to convert my r file to HTML, but it always turns this error even if my code is good to process.
error
Quitting from lines 71-90 (HW1.Rmd)
Error in eval(quote(list(...)), env) : object 'MAD' not found
Calls: <Anonymous> ... [.data.frame -> order -> standardGeneric -> eval -> eval -> eval
Execution halted
error part code
ss <- data.frame(
MED = apply(exprs(ESET),1,median),
MAD = apply(exprs(ESET),1,mad)
)
sort(ss$MAD, decreasing = TRUE)[1:101]
highlight_df <- ss %>%
filter(MAD>3.800260)
ss %>%
ggplot(aes(x=MED,y=MAD)) +
geom_point(pch=20) +
geom_point(data=highlight_df,
aes(x=MED,y=MAD,color = top100),
color='red',
size=3)
top <- ss[order(-MAD,-MED),]
top[1:10,]

xtsible object, looping in quantmod

I would like to loop through a list of stock symbols and print them with chartSeries. It would be easier than always changing the argument. Unfortunatly I always get an error, when I want to loop or subset:
Error in try.xts(x, error = "chartSeries requires an xtsible object"):
chartSeries requires an xtsible object
Here the code that produces the error:
library(quantmod)
stocks <- c("FIS", "AXP", "AVB")
symbols <- (getSymbols(stocks, src='yahoo'))
for (i in symbols){
chartSeries(i, theme="white",
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
}
or only:
chartSeries(symbols[1], theme="white",
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
symbols is a character vector. It's not a list of xts objects. Calling chartSeries on a character vector causes the error.
R> chartSeries("OOPS")
Error in try.xts(x, error = "chartSeries requires an xtsible object") :
chartSeries requires an xtsible object
One solution is to put all the downloaded data into one environment, then call chartSeries on every object in the environment.
library(quantmod)
stocks <- c("FIS", "AXP", "AVB")
stockEnv <- new.env()
symbols <- getSymbols(stocks, src='yahoo', env=stockEnv)
for (stock in ls(stockEnv)){
chartSeries(stockEnv[[stock]], theme="white", name=stock,
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
}

Why can't I vectorize source_url in knitr?

I am trying to vectorize this call to source_url, in order to load some functions from GitHub:
library(devtools)
# Find ggnet functions.
fun = c("ggnet.R", "functions.R")
fun = paste0("https://raw.github.com/briatte/ggnet/master/", fun)
# Load ggnet functions.
source_url(fun[1], prompt = FALSE)
source_url(fun[2], prompt = FALSE)
The last two lines should be able to work in a lapply call, but for some reason, this won't work from knitr: to have this code work when I process a Rmd document to HTML, I have to call source_url twice.
The same error shows up with source_url from devtools and with the one from downloader: somehwere in my code, an object of type closure is not subsettable.
I suspect that this has something to do with SHA; any explanation would be most welcome.
It has nothing to do with knitr or devtools or vectorization. It is just an error in your(?) code, and it is fairly easy to find it out using traceback().
> library(devtools)
> # Find ggnet functions.
> fun = c("ggnet.R", "functions.R")
> fun = paste0("https://raw.github.com/briatte/ggnet/master/", fun)
> # Load ggnet functions.
> source_url(fun[1], prompt = FALSE)
SHA-1 hash of file is 2c731cbdf4a670170fb5298f7870c93677e95c7b
> source_url(fun[2], prompt = FALSE)
SHA-1 hash of file is d7d466413f9ddddc1d71982dada34e291454efcb
Error in df$Source : object of type 'closure' is not subsettable
> traceback()
7: which(df$Source == x) at file34af6f0b0be5#14
6: who.is.followed.by(df, "JacquesBompard") at file34af6f0b0be5#19
5: eval(expr, envir, enclos)
4: eval(ei, envir)
3: withVisible(eval(ei, envir))
2: source(temp_file, ...)
1: source_url(fun[2], prompt = FALSE)
You used df in the code, and df is a function in the stats package (density of the F distribution). I know you probably mean a data frame, but you did not declare that in the code.

Resources