Error in ts(data) : R scoping issue - r

I am running my script
#!/usr/bin/env Rscript
require(gdata)
library('ggplot2')
library('forecast')
library('tseries')
df1 <- read.xls('us-gasprices.xls',header = TRUE)
new = df1$V2
data = tail(new,-1)
data = ts(data)
fit = auto.arima(data, seasonal=FALSE)
png(filename="residuals.png")
tsdisplay(residuals(fit), lag.max=40, main='(4,1,1) Model Residuals')
plot(m)
dev.off()
Output
Error in ts(data) : 'ts' object must have one or more observations
I have read this thread
I understand what Rob has explained that the problem is in scoping.
When I run my code from R terminal line by line then it works fine.
But when I run Rscript in Ubuntu terminal the above-mentioned problem occurs.
How to solve this?

Related

R package development: tests pass in console, but fail via devtools::test()

I am developing an R package that calls functions from the package rstan. As a MWE, my test file is currently set up like this, using code taken verbatim from rstan's example:
library(testthat)
library(rstan)
# stan's own example
stancode <- 'data {real y_mean;} parameters {real y;} model {y ~ normal(y_mean,1);}'
mod <- stan_model(model_code = stancode, verbose = TRUE)
fit <- sampling(mod, data = list(y_mean = 0))
# I added this line, and it's the culprit
summary(fit)$summary
When I run this code in the console or via the "Run Tests" button in RStudio, no errors are thrown. However, when I run devtools::test(), I get:
Error (test_moments.R:11:1): (code run outside of `test_that()`)
Error in `summary(fit)$summary`: $ operator is invalid for atomic vectors
and this error is definitely not occurring upstream of that final line of code, because removing the final line allows devtools::test() to run without error. I am running up-to-date packages devtools and rstan.
It seems that devtools::test evaluates the test code in a setting where S4 dispatch does not work in the usual way, at least for packages that you load explicitly in the test file (in this case rstan). As a result, summary dispatches to summary.default instead of the S4 method implemented in rstan for class "stanfit".
The behaviour that you're seeing might relate to this issue on the testthat repo, which seems unresolved.
Here is a minimal example that tries to illuminate what is happening, showing one possible (admittedly inconvenient) work-around.
pkgname <- "foo"
usethis::create_package(pkgname, rstudio = FALSE, open = FALSE)
setwd(pkgname)
usethis::use_testthat()
path_to_test <- file.path("tests", "testthat", "test-summary.R")
text <- "test_that('summary', {
library('rstan')
stancode <- 'data {real y_mean;} parameters {real y;} model {y ~ normal(y_mean,1);}'
mod <- stan_model(model_code = stancode, verbose = TRUE)
fit <- sampling(mod, data = list(y_mean = 0))
expect_identical(class(fit), structure('stanfit', package = 'rstan'))
expect_true(existsMethod('summary', 'stanfit'))
x <- summary(fit)
expect_error(x$summary)
expect_identical(x, summary.default(fit))
print(x)
f <- selectMethod('summary', 'stanfit')
y <- f(fit)
str(y)
})
"
cat(text, file = path_to_test)
devtools::test(".") # all tests pass
If your package actually imports rstan (in the NAMESPACE sense, not in the DESCRIPTION sense), then S4 dispatch seems to work fine, presumably because devtools loads your package and its dependencies in a "proper" way before running any tests.
cat("import(rstan)\n", file = "NAMESPACE")
newtext <- "test_that('summary', {
stancode <- 'data {real y_mean;} parameters {real y;} model {y ~ normal(y_mean,1);}'
mod <- stan_model(model_code = stancode, verbose = TRUE)
fit <- sampling(mod, data = list(y_mean = 0))
x <- summary(fit)
f <- selectMethod('summary', 'stanfit')
y <- f(fit)
expect_identical(x, y)
})
"
cat(newtext, file = path_to_test)
## You must restart your R session here. The current session
## is contaminated by the previous call to 'devtools::test',
## which loads packages without cleaning up after itself...
devtools::test(".") # all tests pass
If your test is failing and your package imports rstan, then something else may be going on, but it is difficult to diagnose without a minimal version of your package.
Disclaimer: Going out of your way to import rstan to get around a relatively obscure devtools issue should be considered more of a hack than a fix, and documented accordingly...

plotmplier in NARDL package

I have a problem with running plotmplier command in NARDL package. I keep receiving the same error:
error in plot.window(…) :need finite ylim
erd22 <- nardl(ef~lwr,efo,ic="bic",maxlags = TRUE,graph = FALSE,case=3) summary(erd22)
plotmplier(erd22,2,2,10)
Result through NARDL in R Prog is contradicted with Stata and Eviews. F Bound test is not a correct one. Better to use Stata or eviews 9/10.

mlr error in randomForestSRC after first run

I have installed Java 9.0.4 and all the relevant R libraries on macOS 10.13.4 to run the following script in R 3.5.0 (invoked in RStudio 1.1.423):
options("java.home"="/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home/lib")
Sys.setenv(LD_LIBRARY_PATH='$JAVA_HOME/server')
dyn.load('/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home/lib/server/libjvm.dylib')
library(mlr)
library(tidyverse) # for ggplot and data wrangly
library(ggvis) # ggplot visualisation in shiny app
library(rJava)
library(FSelector)
data <- read.csv('week07/PhishingWebsites.csv')
# All variables to nominal (PhishingWebsites)
data[c(1:31)] <- lapply(data[c(1:31)] , factor)
# Configure a classification task and specify Result as the target feature.
classif.task <- makeClassifTask(id = "web", data = data, target = "Result")
fv <- generateFilterValuesData(classif.task)
It works fine the first time I run it, but if I run it a second time I get the following error:
Error in randomForestSRC::rfsrc(getTaskFormula(task), data = getTaskData(task), :
An error has occurred in the grow algorithm. Please turn trace on for further analysis.
Any help much appreciated.

CARET Package in R - createDataPartition() function not found?

I am learning the CARET Package in R and I am trying to run to code in Max Kuhn's paper "A Short Introduction to the caret Package". When I run the following code, after successfully installing CARET:
data(Sonar)
set.seed(107)
# The outcome data are needed, the percentage of data in the training set & the format of the results
inTrain <- createDataPartition(y = Sonar$Class,p = .75, list = FALSE)
str(inTrain)
I get the following error that this function createDataPartition() is not found:
Error in createDataPartition(y = Sonar$Class, p = 0.75, list = FALSE) :
could not find function "createDataPartition"
> str(inTrain)
Error in str(inTrain) : object 'inTrain' not found
Any thoughts?
Best,
Mike
I had the same problem... The solution:
In your shell go to /var/folders/tn/f7md6x8j0b73tg9tp83hgm4r0000gn/T//RtmpChzV5D/downloaded_packages
cd /var/folders/tn/f7md6x8j0b73tg9tp83hgm4r0000gn/T//RtmpChzV5D/downloaded_packages
Look what you have there:
ls
If you have something like caret_6.0-80.tgz, you need to remove it:
sudo rm -r caret_6.0-80.tgz
I hope I've helped :)

R function not working in code

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)

Resources