evaluation inside of test_that call - r

I am trying to write some unit tests for my package and having difficulty getting a test of the gls function from nlme to work. MWE:
library(testthat)
library(nlme)
data(Ovary, package = "nlme")
test_that("getData works.", {
re_order <- sample(nrow(Ovary))
egg_scramble <- Ovary[re_order,]
gls_scramble <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time),
data = egg_scramble)
dat <- getData(gls_scramble)
expect_identical(egg_scramble, dat)
})
For some reason, the getData call cannot find the data within the test environment. Here is the the traceback:
Error: Test failed: 'getData works.'
Not expected: object 'egg_scramble' not found
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls)
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: getData(gls_scramble) at :6
5: getData.gls(gls_scramble)
6: eval(if ("data" %in% names(object)) object$data else mCall$data)
7: eval(expr, envir, enclos).
And yet, evaluating the same code outside of test_that does not lead to an error:
re_order <- sample(nrow(Ovary))
egg_scramble <- Ovary[re_order,]
gls_scramble <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time),
data = egg_scramble)
dat <- getData(gls_scramble)
identical(dat, egg_scramble)

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

error in plot function (variable match was not found)

i am trying to plot my decision tree, but it keeps giving me this error, and i can not figure out what is wrong.
here's the code:
install.packages("foreign")
library("foreign")
install.packages("C50")
library(C50)
setwd("C:\\Users\\hp\\Music\\SefSec_2014_HH_weight new.sav")
df <- read.spss("C:\\Users\\hp\\Music\\SefSec_2014_HH_weight new.sav", to.data.frame = TRUE)
View(df)
summary(df)
#summary(df$C12_21)
controlFactor = C5.0Control(sample=0.7,seed=10,CF=0.25,winnow = TRUE ,minCases = 20)
model = C5.0(df[,c(427,432,437,422,447,452,457,462,467,472,482,487,477,492,497,502,503,504,505,506,507,508)], df[,512], control = controlFactor)
na.omit(df)
summary(model)
plot(model,type="s",main="Descision Tree")
and here's the error:
> plot(model,type="s",main="Descision Tree")
Error in FUN(X[[i]], ...) : Variable match was not found.

Object not found error in anova

I am new to coding and R and am trying to run an anova on my dataset for a project. I am looking for the effect of condition on response times (resp.rt). I keep getting the following error though:
Error in eval(expr, envir, enclos) : object 'resp.rt' not found
Here is my code:
setwd('C:/Users/Dasha/Documents/R/stroop')
files <- list.files(path = ".", pattern = "_stroop.csv")
data_frame <- do.call(rbind,lapply(files,read.csv, header = T))
print(i)
#Change independent variables to factors
data_frame$congruent <- as.factor(data_frame$congruent)
data_frame$session <- as.factor(data_frame$session)
data_frame$participant <- as.factor(data_frame$participant)
model_rt <- lm (resp.rt ~ participant + session + congruent + condition + condition*session, data_frame = data_frame)
anova(model_rt)
Any help would be appreciated!
Your data_frame variable (descriptive) most likely does not have a "resp.rt" field...

Error in eval(expr, envir, enclos) : object 'roll_belt' not found in predict

In the call, at the end of the code, to:
predict(pml_training_rf_model_1, pml_validation$classe)
I get the error:
Error in eval(expr, envir, enclos) : object 'roll_belt' not found
That was because I should be calling the function like this:
predict(pml_training_rf_model_1, pml_validation)
The "roll_belt" attribute does appear in the data frames I am using, so I was clearly making some other mistake, which is now corrected and saved for posterity.
#Start code
rm(list=ls())
library("caret")
library("data.table")
library("randomForest")
set.seed(12345)
pml_training_file <- "pml-training.csv"
pml_testing_file <- "pml-testing.csv"
if (!file.exists(pml_training_file)) {
pml_training_url <- "http://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv"
download.file(pml_training_url, pml_training_file)
}
pml_testing_file <- "pml-testing.csv"
if (!file.exists(pml_testing_file)) {
pml_testing_url <- "http://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv"
download.file(pml_testing_url, pml_testing_file)
}
pml_training_original <- fread(pml_training_file, na.strings=c("NA","#DIV/0!",""), data.table = FALSE, stringsAsFactors = TRUE)
partition_index <- createDataPartition(y=pml_training_original$classe, p=0.6, list = FALSE)
pml_training <- pml_training_original[partition_index,]
pml_validation <- pml_training_original[-partition_index,]
#Remove metadata columns
pml_training <- pml_training[,-c(1:7)]
#Remove columns where the number of NA results is above a given level
na_level = .75
nrow_pml_training = nrow(pml_training)
na_col_nums <- numeric()
for(i in 1:length(pml_training)) {
sum_na = sum(is.na(pml_training[, i]))
if(sum_na/nrow_pml_training >= na_level ) {
na_col_nums <- c(na_col_nums, i)
}
}
pml_training <- pml_training[-na_col_nums]
#Set the columns in the validation data to be the same as those in the training data
pml_training_colnames <- colnames(pml_training)
pml_validation <- pml_validation[, pml_training_colnames]
pml_training_rf_model_1 <- randomForest(classe ~ ., data=pml_training)
#Wrong! pml_training_predictions_1 <- predict(pml_training_rf_model_1, pml_validation$classe)
pml_training_predictions_1 <- predict(pml_training_rf_model_1, pml_validation)
confusionMatrix(pml_validation$classe, pml_training_predictions_1)
The correct code is:
pml_training_rf_model_1 <- randomForest(classe ~ ., data=pml_training)
pml_training_predictions_1 <- predict(pml_training_rf_model_1, pml_validation)
confusionMatrix(pml_validation$classe, pml_training_predictions_1)
Question edited also.

Is it possible to call S4 method directly?

Trying to build a gausspr model and using predict to predict the output. Copying code from predict.gausspr documentation.
data(promotergene)
## create test and training set
ind <- sample(1:dim(promotergene)[1],20)
genetrain <- promotergene[-ind, ]
genetest <- promotergene[ind, ]
## train a support vector machine
gene <- gausspr(Class~.,data=genetrain,kernel="rbfdot",
kpar=list(sigma=0.015))
## predict gene type probabilities on the test set
genetype <- predict(gene,genetest,type="probabilities")
This works fine. Now, when i try to call predict.gausspr directly it's failing. Is it possible to call this S4 method directly ?
Also, is this case with any S4 method or something special in this case ?
> genetype <- predict.gausspr(gene,genetest,type="probabilities")
Error: could not find function "predict.gausspr"
kernlab package is loaded properly and am able to do ?predict.gausspr and see the notes
I guess you mean the gausspr() function from the kernlab package. Using the snippet from ?gausspr I see
library(kernlab)
data(iris)
test <- gausspr(Species~., data=iris, var=2)
predict(test, iris[,-5])
test is indeed an S4 object
> isS4(test)
[1] TRUE
> class(test)
[1] "gausspr"
attr(,"package")
[1] "kernlab"
Discovering S4 methods
S4 methods are discovered using showMethods() and selectMethod() (output edited for brevity)
> showMethods("predict")
Function: predict (package stats)
object="ANY"
object="gausspr"
object="kfa"
object="kha"
object="kpca"
object="kqr"
object="ksvm"
object="lssvm"
object="onlearn"
object="rvm"
> showMethods(class=class(test), where=search())
Function: alphaindex (package kernlab)
object="gausspr"
...
Function: predict (package stats)
object="gausspr"
...
> selectMethod("predict", class Method Definition:
function (object, ...)
{
.local <- function (object, newdata, type = "response", coupler = "minpair")
{
sc <- 0
type <- match.arg(type, c("response", "probabilities",
"votes", "variance"))
...
If there was no relevant predict,gausspr method, then we would end up at predict,ANY-method, which actually invokes the S3 methods discovered by methods("predict").
The help page is discovered with
?"predict,gausspr-method"
Debugging S4 methods
traceback / recover
If a method fails and you'd like to debug it, then usually the simplest thing to do is to use ?traceback to find out where the error occurs, and ?recover to identify the problem in more detail. Here's an error
> predict(test, mtcars)
Error in eval(expr, envir, enclos) : object 'Sepal.Length' not found
and we can see the 'call stack' from 1 (the generic 'predict') to 2 (the method 'predict,gausspr-mehtod') to 3 (the .local function, defined inside the gausspr method), etc.
> traceback()
9: eval(expr, envir, enclos)
8: eval(predvars, data, env)
7: model.frame.default(object, data, xlev = xlev)
6: model.frame(object, data, xlev = xlev)
5: model.matrix.default(delete.response(terms(object)), as.data.frame(newdata),
na.action = na.action)
4: model.matrix(delete.response(terms(object)), as.data.frame(newdata),
na.action = na.action)
3: .local(object, ...)
2: predict(test, mtcars)
1: predict(test, mtcars)
Set the error option (see ?options) to recover and try again, choosing the frame number inside the .local function to be in the body of the method.
> options(error=recover)
> predict(test, mtcars)
Error in eval(expr, envir, enclos) : object 'Sepal.Length' not found
Enter a frame number, or 0 to exit
1: predict(test, mtcars)
2: predict(test, mtcars)
3: .local(object, ...)
4: model.matrix(delete.response(terms(object)), as.data.frame(newdata), na.act
5: model.matrix.default(delete.response(terms(object)), as.data.frame(newdata)
6: model.frame(object, data, xlev = xlev)
7: model.frame.default(object, data, xlev = xlev)
8: eval(predvars, data, env)
9: eval(expr, envir, enclos)
Selection: 3
Called from: eval(predvars, data, env)
Browse[1]> ls()
[1] "coupler" "ncols" "newdata" "nrows" "object" "oldco" "sc"
[8] "type"
Restore normal error behavior with options(error=NULL).
debug / trace
There are a couple of things to do to debug S4 methods. The first is to use the debugger on the selected methods
debug(selectMethod("predict", class(test)))
The second is to trace the method
trace("predict", browser, signature=class(test))
(stop tracing with untrace("predict", signature=class(test))
In this particular case you'll see that the body of the function is in a nested function called .local. Setting the debugger on the outer function is not enough, instead one needs to break in the outer function, then step through until .local has been defined but not evaluated, and set the debugger on .local, like (editing the output for brevity)
> trace(predict, browser, signature=class(test))
Tracing specified method for function "predict" in environment
<namespace:stats>
Warning: Tracing only in the namespace; to untrace you will need:
untrace("predict", where = getNamespace("stats"))
[1] "predict"
attr(,"package")
[1] "stats"
> predict(test, iris[,-5])
Tracing predict(test, iris[, -5]) on entry
Called from: eval(expr, envir, enclos)
Browse[1]> n
debug: {
.local <- function (object, newdata, type = "response", coupler = "minpair")
{
sc <- 0
type <- match.arg(type, c("response", "probabilities",
...
Browse[2]> n
debug: .local(object, ...)
Browse[2]> debug(.local)
Browse[2]> n
debugging in: .local(object, ...)
debug: {
sc <- 0
type <- match.arg(type, c("response", "probabilities", "votes",
...
Browse[3]>
The author of the kernlab package did not provide an S3-style function predict.gausspr, even though the S4 guidelines (?setMethod) suggest that they do. This would have simplified debugging, e.g., debug(kernlab:::predict.gausspr).

Resources