R function not working in code - r

I'm starting to learn Timeseries forcasting in R.
I keep getting an error when running the following code (the last line is the error).
Any ideas?
mydata = read.csv("Sample data.csv", header = FALSE, sep = ",") # read csv file
Revenue_Data <- ts(mydata, frequency=12, start=c(2015,1))
library("forecast")
library("ggplot2")
logRevDataTimeSeries <- log(Revenue_Data)
RevForecasts <- HoltWinters(logRevDataTimeSeries)
RevForecasts$SSE
[1] 0.141991
RevForecasts2 <- forecast.HoltWinters(RevForecasts, h=48)
Error in forecast.HoltWinters(RevForecasts, h = 48) :
could not find function "forecast.HoltWinters"

You need to call forecast not forecast.HoltWinters. forecast.HoltWinters specifies that the forecast function can be applied to a HoltWinters object.
See the help page for further details: https://www.rdocumentation.org/packages/forecast/versions/8.1/topics/forecast.HoltWinters

I found one simple way to get the output with holtwinnter. Try this
holtwinnter_fit <- holt(training_data$predictor)

Related

What does "invalid type (closure) for variable 'variable1'" mean and how do I fix it?

I am trying to write a function in R, which contains a function from another package. The code works perfectly outside a function.
I am guessing, it might have got to do something with the package I am using (survey).
A self-contained code example:
#activating the package
library(survey)
#getting the dataset into R
tm <- read.spss("tm.sav", to.data.frame = T, max.value.labels = 5)
# creating svydesign object (it basically contains the weights to adjust the variables (~persgew: also a column variable contained in the tm-dataset))
tm_w <- svydesign(ids=~0, weights = ~persgew, data = tm)
#getting overview of the welle-variable
#this variable is part of the tm-dataset. it is needed to execute the following steps
table(tm$welle)
# data manipulation as in: taking the v12d_gr-variable as well as the welle-variable and the svydesign-object to create a longitudinal variable which is transformed into a data frame that can be passed to ggplot
t <- svytable(~v12d_gr+welle, tm_w)
tt <- round(prop.table(t,2)*100, digits=0)
v12d <- tt[2,]
v12d <- as.data.frame(v12d)
this is the code outside the function, working perfectly. since I have to transform quite a few variables in the exact same way, I aim to create a function to save up some time.
The following function is supposed to take a variable that will be transformed as an argument (v12sd2_gr).
#making sure the survey-object is loaded
tm_w <- svydesign(ids=~0, weights = ~persgew, data = data)
#trying to write a function containing the code from above
ltd_zsw <- function(variable1){
t <- svytable(~variable1+welle, tm_w)
tt <- round(prop.table(t,2)*100, digits=0)
var_ltd_zsw <- tt[2,]
var_ltd_zsw <- as.data.frame(var_ltd_zsw)
return(var_ltd_zsw)
}
Calling the function:
#as v12d has been altered already, I am trying to transform another variable v12sd2_gr
v12sd2 <- ltd_zsw(v12sd2_gr)
Console output:
Error in model.frame.default(formula = weights ~ variable1 + welle, data = model.frame(design)) :
invalid type (closure) for variable 'variable1'
Called from: model.frame.default(formula = weights ~ variable1 + welle, data = model.frame(design))
How do I fix it? And what does it mean to dynamically build a formula and reformulating?
PS: I hope it is the appropriate way to answer to the feedback in the comments.
Update: I think I was able to trace the problem back to the argument I am passing (variable1) and I am guessing it has got something to do with the fact, that I try to call a formula within the function. But when I try to call the svytable with as.formula(svytable(~variable1+welle, tm_w))it still doesn't work.
What to do?
I have found a solution to the problem.
Here is the tested and working function:
ltd_test <- function (var, x, string1="con", string2="pro") {
print (table (var))
x$w12d_gr <- ifelse(as.numeric(var)>2,1,0)
x$w12d_gr <- factor(x$w12d_gr, levels = c(0,1), labels = c(string1,string2))
print (table (x$w12d_gr))
x_w <- svydesign(ids=~0, weights = ~persgew, data = x)
t <- svytable(~w12d_gr+welle, x_w)
tt <- round(prop.table(t,2)*100, digits=0)
w12d <- tt[2,]
w12d <- as.data.frame(w12d)
}
The problem appeared to be caused by the svydesgin()-fun. In its output it produces an object which is then used by the formula for svytable()-fun. Thats why it is imperative to first create the x_w-object with svydesgin() and then use the svytable()-fun to create the t-object.
Within the code snippet I posted originally in the question the tm_w-object has been created and stored globally.
Thanks for the help to everyone. I hope this is gonna be of use to someone one day!

I have problems with a function to impose monotonicity

I am new in R. I am trying to impose monotonicity conditions to a translog production function. I am using the function translogMonoRestr. I loaded my data, the coeff and the inv of the var cov matrix. I imported this from excel and all good
read_excel("rtl2.xlsx")
uCoef <- read_excel("matrixbtl2.xlsx")
uCovInv <- read_excel("matrixinvtl2.xlsx")
but when I tried:
monoRestr <- translogMonoRestr( xNames, = c( "lx1", "lx2"), rtl2.xlsx , dataLogged = TRUE)
I got Error in testNames %in% allNames : object 'rtl2' not found.
Then I'll use solve.QP but that is another topic.
I hope someone can help me with this error message
Thanks

getting error in mclust-package while working on univariate fit

While working on a univariate fit using Mclust I am getting following error:
Error in mstepE(data = as.matrix(data)[initialization$subset, ], z = z, :
row dimension of z should equal data length
I am using the code mentioned in:
https://cran.r-project.org/web/packages/mclust/vignettes/mclust.html#initialisation
This is the code section where I am getting error:
df1 <- dataSample
BIC <- NULL
for(j in 1:20){
rBIC <- mclustBIC(df1, verbose = T,
initialization = list(hcPairs = randomPairs(df1)))
BIC <- mclustBICupdate(BIC, rBIC)
}
summary(BIC)
Following link contains data to be passed to variable 'df1' (file name:dataSample.csv)
https://drive.google.com/open?id=0Bzau9RsRnQreYk9XOWVBSm91b2o4NTQ4RlA2UFdWbDBVOVpR
This is the solution I get from one of the Authors (Prof. Luca Scrucca) for 'mclust' library:
"there was a bug due to the use of automatic subset that clash when hcPairs are provided. I have fixed it in the current dev version of mclust.
Since submission to CRAN won't happen shortly, you may use the following code to avoid the error with the current release of mclust:
rBIC <- mclustBIC(df1, verbose = T,
initialization = list(hcPairs = randomPairs(df1),
subset = 1:NROW(df1)))
When the bug fix will be released, the subset argument could be omitted as it is redundant."
Now, the code is working fine.

rdirichlet distribution isn't working in R

I am attempting to run some code I wrote over a year ago and for some reason it is not working this time. Previously I had the matrix variables alpha and prob typed into R. However this time I am importing them as csv files so it's easier for me to modify them with each itteration. I'm currently running R x64 2.12.2. I loaded gtools, splines and stat4 packages.
alpha <- read.csv("AlphaOriginal.csv", header = FALSE)
prior <- array(0,c(45,45))
for (j in 1:45) prior[j,] <- rdirichlet(1,alpha[j,])
prob <- read.csv("ProbOriginal.csv", header = FALSE)
data <- array(0,c(45,45))
for (i in 1:45) data[i,] <- rmultinom(1,1,prob[i,])
posterior <- data%*%prior
write.table(posterior, file = "PosteriorOriginal.csv", row.names = FALSE, na = "", col.names = FALSE, sep = ",")
After the rdirichlet line I get the following error.
Error in rgamma (1*n, alpha) : invalid arguments
Does anyone know what this error means and how to fix it? Thx
If you take a look at the 'rdirichlet' help page you will find that the 'alpha' argument must be a vector, not a data.frame. So you should instead do:
rdirichlet(1, unlist(alpha[j,]))

Problem when doing pre-whitening before ccf analysis

I have following R code which does not work when trying to pre-whiten other series by the model generated for the other series.
-- Libraries;
library(forecast);
library(TSA);
library(xts);
-- Read from csv;
....
-- Do transforms;
Power=xts(data1[2],seq(from=as.Date("2011-01-01"), to=as.Date("2013-09-18"),by="day"),frequency=7);
Temp=xts(data2[1],seq(from=as.Date("2011-01-01"), to=as.Date("2013-09-18"),by="day"),frequency=7);
-- Prewhiten for CCF;
mod1=Arima(Temp,order=c(2,0,1),seasonal=list(order=c(1,1,1)));
Box.test(mod1$residuals,lag=365,type=c("Ljung-Box"));
x_series=mod1$residuals;
y_filtered=residuals(Arima(Power,model=mod1));
Last Part does not work since I get error:
Error in stats::arima(x = x, order = order, seasonal = seasonal, include.mean = include.mean, :
wrong length for 'fixed'
What goes wrong here?
Arima and stats::arima both require ts objects. The error is caused by xts objects being used. Try this instead:
Power <- ts(data1[2], frequency=7)
Temp <- ts(data2[1], frequency=7)
mod1 <- Arima(Temp,order=c(2,0,1),seasonal=c(1,1,1))
Box.test(residuals(mod1),lag=365,type=c("Ljung-Box"))
x_series <- residuals(mod1)
y_filtered <- residuals(Arima(Power,model=mod1))

Resources