Object not found error when passing model formula to another function
When you created your formula, lm.cars
, in was assigned its own environment. This environment stays with the formula unless you explicitly change it. So when you extract the formula with the formula
function, the original environment of the model is included.
I don't know if I'm using the correct terminology here, but I think you need to explicitly change the environment for the formula inside your function:
cv.step <- function(linmod,k=10,direction="both"){
response <- linmod$y
dmatrix <- linmod$x
n <- length(response)
datas <- linmod$model
.env <- environment() ## identify the environment of cv.step
## extract the formula in the environment of cv.step
form <- as.formula(linmod$call, env = .env)
## The rest of your function follows
Using formula to predict inside of R function generates `object not found` error
For some reason the lme
function expects a literal formula to be in the call. It does not expect to see a variable there. It uses nonstandard evaluation to try to separate the response from the fixed effect terms. In this case, it really doesn't have to do with the environment of the formula.
The easiest way around this would be to inject the formulas into the call with do.call
. This should work
make_prediction_nlm <- function(data_in,y_var,x_var,treatment_var ,id_var,new_data){
formula_used_nlm <- as.formula(paste(y_var, paste(x_var, treatment_var, sep = " * "), sep = " ~ "))
random_used <- as.formula(paste("~1|",id_var,sep = ""))
lme_model <- do.call("lme", list(fixed = formula_used_nlm,
random = random_used,
data = quote(data_in)))
predict(lme_model, newdata = new_data)
}
This only really affects the predict
function when you pass newdata=
because it goes back to see what the original call was.
R - object formula not found inside a function
You can just wrap y ~ x + I(x^2)
in quotation marks ("y ~ x + I(x^2)"
).
Object [x] not found' When Testing a Custom Formula
I am not sure how the pot_revenue_calc
function need to behave but here are some pointers which might help you to calrify what needs to be done.
Case 1 :
When weekly_rate != 0
and mins > gp
, pot_revenue
is first referred at this line
pot_revenue <- weekly_rate*num_of_weeks(mins, num_days)
Case 2:
When mins <= gp
(irrespective of the value of weekly_rate
), pot_revenue
is first referred at this line
if (mins <= gp) {
pot_revenue <- 0
}
Case 3 :
When weekly_rate == 0
and mins > gp
, pot_revenue
is first referred at this line
pot_revenue <- pot_revenue + (number_of_full_days(mins, num_days, weekly_rate, rollover = FALSE)*dmax)
You calculate pot_revenue
using the value of pot_revenue
which does not exist. This case needs to be fixed. Maybe remove the if
condition from case 2 and initialize to 0 by default.
Apart from that you also don't need if (rollover == TRUE)
, you can do if(rollover)
.
object '...' not found in R Functions with lm -- (Error in eval(predvars, data, env) : object '...' not found)
One of the coolest ways of doing this is using the new recipes package to generate the formula for us and then manipulating a tibble to produce or result
library(tidyverse)
library(recipes)
#>
#> Attaching package: 'recipes'
#> The following object is masked from 'package:stringr':
#>
#> fixed
#> The following object is masked from 'package:stats':
#>
#> step
library(moderndive)
score_model_Fxn <- function(df,x, y){
formula_1 <- df %>%
recipe() %>%
update_role({{x}},new_role = "outcome") %>%
update_role({{y}},new_role = "predictor") %>%
formula()
Reg_Table <- mtcars %>%
summarise(score_mod = list(lm(formula_1,data = .))) %>%
rowwise() %>%
mutate(Reg_Table = list(get_regression_table(score_mod))) %>%
pull(Reg_Table)
print(paste('The regression table is', Reg_Table))
Reg_Table
}
k <- mtcars %>%
score_model_Fxn(x = cyl,y = gear)
#> [1] "The regression table is list(term = c(\"intercept\", \"gear\"), estimate = c(10.585, -1.193), std_error = c(1.445, 0.385), statistic = c(7.324, -3.101), p_value = c(0, 0.004), lower_ci = c(7.633, -1.978), upper_ci = c(13.537, -0.407))"
k
#> [[1]]
#> # A tibble: 2 x 7
#> term estimate std_error statistic p_value lower_ci upper_ci
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 intercept 10.6 1.44 7.32 0 7.63 13.5
#> 2 gear -1.19 0.385 -3.10 0.004 -1.98 -0.407
Created on 2020-06-09 by the reprex package (v0.3.0)
object not found within function: nlmer edition
It seems nlmer
has an odd way of parsing the formula you pass to the function. You apparently cannot pass a variable that's not defined in the global environment. This seems to be because the nlformula
calls as.formula
on the unevaluated symbol that's pass as in as the formula. This means that lexical scoping is used to resolve the symbols so it's searching for model_formula
in the stats
namespace and then the global environment and not in the scope defined by your function.
A work-around would be to evaluate that parameter and then pass along that value via do.call()
, for example
run_nonlin<- function(model_formula, data){
Model<- ~b0+b2*exp(-b3*time)
ModelGradient<-deriv(Model,namevec=c("b0","b2","b3"),
function.arg=c("time","b0","b2","b3"))
out <- do.call('nlmer', list(as.formula(model_formula),
data=quote(data),
start = c(b0=3,b2=1,b3=4),
control=nlmerControl(optimizer="bobyqa",
optCtrl=list(maxfun=200000))))
return(out)
}
Related Topics
How to Tell the R Interpreter How to Use the Proxy Server
Leaflet Legend for Custom Markers in R
Output in R, Avoid Writing "[1]"
How to Facet a Plot_Ly() Chart
Combining New Lines and Italics in Facet Labels with Ggplot2
Convert Factor to Integer in a Data Frame
Matching a Sequence in a Larger Vector
Count Number of Non-Na Values for Every Column in a Dataframe
What Does "Not Run" Mean in R Help Pages
How to Install Roracle Package on Windows 7
Export Data Frames to Excel via Xlsx with Conditional Formatting
Object Not Found Error When Passing Model Formula to Another Function
How to Get the Number of Rows in a CSV File Without Opening It
How to Add Annotations Below the X Axis in Ggplot2
How to Find the Indices of the Top 10,000 Elements in a Symmetric Matrix(12K X 12K) in R
Dplyr Piping Data - Difference Between '.' and '.X'