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".
Related
My fingers are starting to tire of typing update.packages(checkBuilt = T, ask = F). I was wondering whether it's possible to redefine the default parameters within the update.packages() function. So far, I've tried adding the following to my .Rprofile file:
utils::assignInNamespace(
"update.packages",
function(checkBuilt = TRUE, ask = FALSE, ...) {
update.packages(checkBuilt = checkBuilt, ask = ask, ...)
},
"utils"
)
But when I try to use the function in R I get the following error:
update.packages()
Error: C stack usage 7976404 is too close to the limit
I've also just tried using formals() with the following in the .Rprofile:
local({
args_new <- alist(lib.loc = .libPaths(), ask = FALSE, checkBuilt = TRUE)
ind <- which(methods::formalArgs(update.packages) %in% names(args_new))
formals(update.packages)[ind] <- args_new
})
But that results in the following error upon launching R:
Error in formals(update.packages) : object 'update.packages' not found
As #Roland said in the comments, your definition is recursive. You shouldn't bother with the assignInNamespace: keeping the new function in your workspace is good enough. Then you can use utils::update.packages in its definition, e.g.
update.packages <- function(checkBuilt = TRUE, ask = FALSE, ...)
utils::update.packages(checkBuilt = checkBuilt, ask = ask, ...)
You should avoid using assignInNamespace for the reasons listed in its help page.
I have written a function in R which extracts data from a database and builds a new table.
My new table is labeled with the date of the extract (build_date_0).
When I'm debugging my function I get the following warning when I look at my date string:
Browse[2]> build_date_0
[1] "2019-05-01"
Warning message:
In get(object, envir = currentEnv, inherits = TRUE) :
restarting interrupted promise evaluation
Questions:
What does this warning mean / what is happening (step-by-step/basics)?
Should I care?
In general how can I find out more about this error?
This is my code:
build_account_db = function(conn = connection_object
,various_inputs = 24){
browser()
# create connection objects
tabs_1 = dplyr::tbl(conn,in_schema("DB_1","VIEW_W") # some table
# create date string
build_date_0 = lubridate::today() %>% as.character()
build_date = str_replace_all(build_date_0,"-+","_")
db_name_1 = paste0('DATABASE.tab_1_',build_date)
db_name_2 = paste0('DATABASE.tab_2_',build_date)
# build query
query_text_1 = tabs_1 %>% select(COL_1) # some query
query_text_1 = tabs_1 %>% select(COL_2)
# build new tables
create_db = DBI::dbSendQuery(conn_t,paste('CREATE TABLE',db_name_1,'AS (',query_text_1,') WITH DATA PRIMARY INDEX (ID_1)'))
create_db2 = DBI::dbSendQuery(conn_t,paste('CREATE TABLE',db_name_2,'AS (',query_text_2,') WITH DATA PRIMARY INDEX (ID_1)'))
}
When I check a variable, I may or may not get this warning (it varies, even if I restart R, and run my code again with a cleared environment)
Browse[2]> build_date
[1] "2019-02-28 11:00:00 AEDT"
Warning message:
In get(object, envir = currentEnv, inherits = TRUE) :
restarting interrupted promise evaluation
What I've tried: I read this question, but it's more about suppressing the error. Also, google.
I found this link on promises and evaluation in R helpful for a related problem: https://mailund.dk/posts/promises-and-lazy-evaluation/. I wonder if after build_date_0 = lubridate::today() %>% as.character() if you add a call to just build_date_0 if that would solve the promise? Good luck!
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.
in the following function I have to use the bquote function when fitting the gam model to avoid the error
Error in eval(expr, envir, enclos) : object 'x' not found
when plot.gam is called. The error occurs due to the factor variable I want to plot. However I don't really understand what the bquote does here and why I need it.
library(mgcv)
plot_model <- function(x){
# agam <- gam(mean ~ s(bla) + bla2, data=x)
agam <- eval(bquote(mgcv::gam(mean ~ s(bla) + bla2, data=.(x))))
plot(agam, pages=1, all.terms = TRUE)
}
bla <- data.frame(bla=rnorm(20), bla2=sample(letters[1:4], size=20, replace=T),
mean=sample(20))
plot_model(bla)
The R-help says "bquote quotes its argument except that terms wrapped in .() are evaluated in the specified where environment. Usage bquote(expr, where = parent.frame())." What is the where environment here (parent.frame = the plot_model environment?) and what environment would it be evaluated in without the bquote (the environment created by the call to gam?)?
bquote substitutes the expression .(X) with the value of x. Therefore what is actually evaluated is:
mgcv::gam(mean ~ s(bla) + bla2, data = list(bla = c(-0.147370861075094, <...>)
This error pops up because plot.gam asks to look for the symbol x in the global environment rather than the environment of plot_model.
When debugged with recover:
<...>
3: plot.gam(agam, pages = 1, all.terms = TRUE)
4: termplot(x, se = se, rug = rug, col.se = 1, col.term = 1, main = attr(x$pterms, "term.
5: eval(model$call$data, envir)
<...>
Browse[1]> envir
<environment: R_GlobalEnv>
After searching the forum, I did not find similair questions. If you find one, please let me know. I would really appreciate.
In R, I need to check the return values from function Gammad and Truncate (from lib distr and truncdist).
It means that if they fail to generate the Gammad and Truncate pdf, a fail value or exception can be returned so that I can handle it.
G0 <- Gammad(scale = s, shape = sh)
# what if Gammad() fails ?
TG <- Truncate(G0, lower = lowerbound, upper = upperbound)
# what if Truncate() fails ?
Thanks !
From the rgamma help page: "Invalid arguments will result in return value NaN, with a warning."
If this is what you see, you could use
ow <- options("warn")
options(warn=2)
G0 <- try(Gammad(scale = s, shape = sh), silent=TRUE)
if(inherits(G0, "try-error")) # handle invalid arguments
options(warn=ow)