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

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

Related

R Model returning the error: Too many open devices

I've been working on the creation of a training model in R for MS Azure. When I initially set up the model it all worked fine. Now it's continuously returning the below:
{"error":{"code":"LibraryExecutionError","message":"Module execution encountered an internal library error.","details":[{"code":"FailedToEvaluateRScript","target":"Score Model (RPackage)","message":"The following error occurred during evaluation of R script: R_tryEval: return error: Error in png(file = \"3e25ea05d5bc49d683f4471ff40780bcrViz%03d.png\", bg = \"transparent\") : \n too many open devices\n"}]}}
I haven't changed anything, and have looked around online only to find references to other issues. My code is as follows:
Trainer R Script
# Modify Datatype, factor Level, Replace NA to 0
x <- dataset
for (i in seq_along(x)) {
if (class(x[[i]]) == "character") {
#Convert Type
x[[i]] <- type.convert(x[[i]])
#Apply Levels
# levels(x[[i]]) <- levels(cols_modeled[, names(x)[i]]) # linked with levels in model
}
if (is.numeric(x[[i]]) && is.na(x[[i]]) ){
#print("*** Updating NA to 0")
x[[i]] <- 0
}
}
df1 <- x
rm(x)
set.seed(1234)
model <- svm(Paid ~ ., data= df1, type= "C")
Scorer R Script
library(e1071)
scores <- data.frame( predicted_result = predict(model, dataset))
Has anyone come across this before?

Error in boot.ci() function in R

I am trying to calculate bootstrap confidence intervals.
Here is my code.
library(boot)
nboot <- 10000 # Number of simulations
alpha <- .01 # alpha level
n <- 1000 # sample size
bootThetaQuantile <- function(x,i) {
quantile(x[i], probs=.5)
}
raw <- rnorm(n,0, 1) # raw data
( theta.boot.median <- boot(raw, bootThetaQuantile, R=nboot) )
boot.ci(theta.boot.median, conf=(1-alpha)) #this causes no error
boot.ci(theta.boot.median, conf=(1-alpha), type = "percent") #this causes an error
The error message reads "Error in ci.out[[4L]] : subscript out of bounds". I am very confused by this because I am not sure why the call to boot.ci will cause an error when the previous line caused no error.
That is because you have to use type = 'perc'.
boot.ci(theta.boot.median, conf=(1-alpha), type = "perc")

replacement has length zero in list() in r

I'm trying to run this code, and I'm using mhadaptive package, but the problem is that when I run these code without writing metropolis_hastings (that is one part of mhadaptive package) error does not occur, but when I add mhadaptive package the error occur. What should I do?
li_F1<-function(pars,data) #defining first function
{
a01<-pars[1] #defining parameters
a11<-pars[2]
epsilon<<-pars[3]
b11<-pars[4]
a02<-pars[5]
a12<-pars[6]
b12<-pars[7]
h<-pars[8]
h[[i]]<-list() #I want my output is be listed in the h
h[[1]]<-0.32082184 #My first value of h is known and other values should calculate by formula
for(i in 2:nrow(F_2_))
{
h[[i]]<- ((a01+a11*(h[[i-1]])*(epsilon^2)*(h[[i-1]])*b11)+(F1[,2])*((a02+a12*(h[[i-1]])*(epsilon^2)+(h[[i-1]])*b12)))
pred<- h[[i]]
}
log_likelihood<-sum(dnorm(prod(h[i]),pred,sd = 1 ,log = TRUE))
return(h[i])
prior<- prior_reg(pars)
return(log_likelihood + prior)
options(digits = 22)
}
prior_reg<-function(pars) #defining another function
{
epsilon<<-pars[3] #error
prior_epsilon<-pt(0.95,5,lower.tail = TRUE,log.p = FALSE)
return(prior_epsilon)
}
F1<-as.matrix(F_2_) #defining my importing data and simulatunig data with them
x<-F1[,1]
y<-F1[,2]
d<-cbind(x,y)
#using mhadaptive package
mcmc_r<-Metro_Hastings(li_func = li_F1,pars=c(10,15,10,10,10,15),par_names=c('a01','a02','a11','a12','b11','b12'),data=d)
By running this code this error occur.
Error in h[[i]] <- list() : replacement has length zero
I'll so much appreciate who help me.

Error: object not found - cor.ci

I'm trying to use cor.ci to obtain polychoric correlations with significance tests, but it keeps giving me an error message. Here is the code:
install.packages("Hmisc")
library(Hmisc)
mydata <- spss.get("S-IAT for R.sav", use.value.labels=TRUE)
install.packages('psych')
library(psych)
poly.example <- cor.ci(mydata(nvar = 10,n = 100)$items,n.iter = 10,poly = TRUE)
poly.example
print(corr.test(poly.example$rho), short=FALSE)
Here is the error message it gives:
> library(psych)
> poly.example <- cor.ci(mydata(nvar = 10,n = 100)$items,n.iter = 10,poly = TRUE)
Error in cor.ci(mydata(nvar = 10, n = 100)$items, n.iter = 10, poly = TRUE) :
could not find function "mydata"
> poly.example
Error: object 'poly.example' not found
> print(corr.test(poly.example$rho), short=FALSE)
Error in is.data.frame(x) : object 'poly.example' not found
How can I make it recognize mydata and/or select certain variables from this dataset for the analysis? I got the above code from here:
Polychoric correlation matrix with significance in R
Thanks!
You have several problems.
1) As previously commented upon, you are treating mydata as a function, but you need to treat it as a data.frame. Thus the call should be
poly.example <- cor.ci(mydata,n.iter = 10,poly = TRUE)
If you are trying to just get the first 100 cases and the first 10 variables, then
poly.example <- cor.ci(mydata[1:10,1:100],n.iter = 10,poly = TRUE)
2) Then, you do not want to run corr.test on the resulting correlation matrix. corr.test should be run on the data.
print(corr.test(mydata[1:10,1:100],short=FALSE)
Note that corr.test is testing the Pearson correlation.

Error in <my code> : object of type 'closure' is not subsettable (2)

I know this question has been raised before (Error in <my code> : object of type 'closure' is not subsettable). But I could not get my head around it.
Here is the packages I use and how I prepare my data
library(mlogit)
data(CollegeDistance, package="AER")
Data <- CollegeDistance
Data$Dist[Data$distance<0.4] <- 1
Data$Dist[Data$distance<1 & Data$distance>=0.4] <- 2
Data$Dist[Data$distance<2.5 & Data$distance>=1] <- 3
Data$Dist[Data$distance>=2.5] <- 4
Now when I define a mlogit object and use it for prediction I get that error.
Formula <- paste('Dist ~', paste('1|',paste(c("urban", "unemp", "tuition"), collapse = " + "),'|1'))
Model <- mlogit(as.formula(Formula), Data, shape='wide', choice='Dist')
Predict <- predict(Model, newdata=mlogit.data(Data, shape='wide', choice='Dist'), returnData=FALSE)
The interesting part is that if I replace Formula with formulathen it works!
UPDATE
I encounter that problem while using mlogit in a function. I really appreciate it if you can show me a way out of it.
modelmaker <- function(variables){
Formula <- paste('Dist ~', paste('1|',paste(variables, collapse = " + "),'|1'))
MODEL <- mlogit(as.formula(Formula), Data, shape='wide', choice='Dist')
return(MODEL)
}
Model <- modelmaker(c("urban", "unemp", "tuition"))
Predict <- predict(Model, newdata=mlogit.data(Data, shape='wide', choice='Dist'), returnData=FALSE)
This time is does not solve even by avoiding using formula or Formula. If you change it to XXX the error will be
object 'XXX' not found

Resources