running predict for glm in batch mode - r

I try to run
ltv_pos_model$prob3 <- predict(tree_before_deposit_3m_equal_100, newdata = ltv_pos_model,
type = "response")
in batch mode and this is what I get:
Error in get(ctr, mode = "function", envir = parent.frame()) :
object 'contr.Treatment' of mode 'function' was not found
Calls: predict ... model.matrix -> model.matrix.default -> contrasts -> get
Execution halted
In interactive mode everything is OK
Thanks

Related

Prediction using a refund::pfr model

I'm trying to perform prediction of a testing set using a refund::pfr model. My model is scalar-on-function and on scalar and looks like the following example. When I'm using lf(cca) for the functional predictor I get the predictions without problem.
data(DTI)
DTI_train <- DTI[DTI$visit==1 & complete.cases(DTI),]
DTI_train <- DTI_train[1:60, ]
DTI_test <- DTI[DTI$visit==1 & complete.cases(DTI),]
DTI_test <- DTI_test[61:66, ]
fit_lf <- pfr(pasat ~ sex + case + lf(cca), data = DTI_train)
predict(fit_lf, newdata = as.list(DTI_test))
However, when I'm using fpc(cca) I'm getting the following error.
fit_fpc <- pfr(pasat ~ sex + case + fpc(cca), data = DTI_train)
predict(fit_fpc, newdata = as.list(DTI_test))
Error in eval(predvars, data, env) : object 'X.tmat' not found
Calls: predict ... eval -> model.frame -> model.frame.default -> eval -> eval
In addition: Warning message:
In (function (object, newdata, type = "link", se.fit = FALSE, terms = NULL, :
not all required variables have been supplied in newdata!
Calls: predict -> predict.pfr -> eval -> eval -> <Anonymous>
I have tried to include the X.tmat of the newdata by including in the list of newdata the fpc(newdata) but I'm getting another type of problem.
new_fit <- as.list(DTI_test)
new_fit$cca <- fpc(DTI_test[,'cca' ])
predict(fit_fpc, newdata = new_fit)
Error in predict.pfr(fit_fpc, newdata = new_fit) :
length(unique(sapply(newdata, function(x) ifelse(is.matrix(x), .... is not TRUE
Calls: predict -> predict.pfr -> stopifnot
Any idea of how to perform predictions with fpc on my model?
Thanks

Simple regression linreg error in R: argument 'modeltest'must be either TRUE or FALSE

Hello everyone I am having an issue with my R software. When I try to run a simple regression i get this error:
model1 <- linReg(data = dat, dep = 'Intent', blocks = list(c('Enjoy')), modelTest = 'f', stdEst = TRUE)
model1
Error: Argument 'modelTest' must be either TRUE or FALSE
I have tried changing the to a capital and typing in FALSE instead but when I type in FALSE I get this error:
model1 <- linReg(data = dat, dep = 'Intent', blocks = list(c('Enjoy')), modelTest = FALSE, stdEst = TRUE)
Error in eval(predvars, data, env) : object 'XRW5qb3k' not found
Can anyone please help me with this? All o the descriptives, graphs, and plots run just fine. I have the packages jmv, psych, and car loaded
Thank you for your help!

R CARET : Error 3 arguments passed to 'is.nan' which requires 1

CODE:
seedx=12345
set.seed(seedx)
train_control1 <- trainControl(method="repeatedcv", number=5, repeats=50, savePredictions="final", classProbs=TRUE, summaryFunction=twoClassSummary)
train_control1$sampling<-"smote"
set.seed(seedx);
rfxmod <- train(vardep~., data = training, method ='rf', metric='ROC', trControl =train_control1)
I am having the following error:
Error in { :
task 1 failed - "3 arguments passed to 'is.nan' which requires 1"
Calls: train ... train.default -> nominalTrainWorkflow -> %op% ->
Execution halted
traceback()
8: stop(simpleError(msg, call = expr))
7: e$fun(obj, substitute(ex), parent.frame(), e$data)
6: foreach(iter = seq(along = resampleIndex), .combine = "c", .verbose = FALSE,
.export = export, .packages = "caret") %:% foreach(parm = 1L:nrow(info$loop),
.combine = "c", .verbose = FALSE, .export = export, .packages = "caret") %op%
{
if (!(length(ctrl$seeds) == 1 && is.na(ctrl$seeds)))
set.seed(ctrl$seeds[[iter]][parm])
loadNamespace("caret")
I tested different seed/folds/repeats still same error. I also re-installed the latest R software.
I tested the same dataset and same code with another PC and it works.
Does anyone have any idea?
I think the problem is the seeds. But I don't seem to able to rule it out.
It does it even with XGBTREE and GLMNET.
I also created my own multifolds/tunegrid and seeds and still not working.
Thanks

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).

Error in get(as.character(FUN), mode = "function", envir = envir)

I am new to R, so forgive me if the question is a little silly.
I am trying to write a simple while loop for a value function iteration. My function (optim.routine) uses the solver ipoptr. Here is my code:
d<-1
old1<-0
old2<-0
num.iter<-0
i.esp<-1e-05
i.T<-100
lb<-0
ub<-10
while (d>i.eps & num.iter<i.T){
new1 <- optim.routine(old1, old2, eval_f=eval_f, eval_grad_f=eval_grad_f, lb=lb, ub=ub, update=FALSE)
d<-dist(c(old1, new1), method="euclidean")
num.iter<-num.iter+1
old1<-new1
}
where optim.routine is the following function:
optim.routine<-function(old1, old2, eval_f=obj, eval_grad_f=obj.deriv, lb=lb, ub=ub, update){
if (isTRUE(update)){
var2<-old2
var1<-old1
var1.deriv<-deriv(var1)
optimize <- ipoptr(x0 = old2, eval_f = eval_f, eval_grad_f = eval_grad_f, lb = lb,
ub = ub)
new1<- optimize$objective
new2<- optimize$solution
old2<-new2
old1<-new1
}else{
var2<-old2
var1<-old1
var1.deriv<-vf.deriv(var1)
optimize <- ipoptr(x0 = old2, eval_f = eval_f, eval_grad_f = eval_grad_f, lb = lb,
ub = ub)
new1<- optimize$objective
new2<- optimize$solution
old1<-new1
}
}
and deriv is a function that computes derivatives.
I get the following error if i try to run the code:
source('/mnt/ide0/home/myname/Documents/optim.R')
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'fn' of mode 'function' was not found
and if I debug the function:
Browse[2]> n
Error in isTRUE(update) : argument "update" is missing, with no default
If I only source the function without the while loop no error is displayed. Honestly, I have no clue. Any help is greatly appreciated. Thanks!
Claudia
I had exactly the same error message when I named a variable with the
same name of an existing function in R. I've found this tip
here: http://notepad.patheticcockroach.com/2565/a-bad-idea-in-r-using-variables-with-the-same-name-as-existing-functions/ Hope it helps you too.
– FraNut Oct 12 at 11:26
He's right refrain from using variables that might be function names too.
e.g
z1<-aggregate(steps ~ interval, data_df, mean)
mean<-mean(z[,2],na.rm = TRUE)
mean is a variable and a function name passed as an argument to the aggregate function causing a conflict
Many times that error will appear when you previously created an object called "mean" in the R environment. This creates a conflict when calling the function "mean". To stop this error use:
rm(mean)
This removes the object "mean" from the environment and allows R to call the function "mean".

Resources