Based on the provided code and error message, I’ll provide a step-by-step solution.
Step 1: Identify the issue
The make_prediction_nlm function is trying to use the lme function with a formula as an argument. However, when called with new_data = fake_data_complicated_1, it throws an error saying that the object ‘formula_used_nlm’ is not found.
Step 2: Understand the lme function’s behavior
The lme function expects to receive literal formulas as arguments, rather than variables or expressions containing variables. The non-standard evaluation in R allows for more flexibility, but it also means that variables and expressions must be handled carefully.
Step 3: Use do.call to inject the formulas into the call
To overcome this issue, you can use do.call to explicitly pass the formula as an argument to the lme function. Here’s how you can modify your code:
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)
}
In this modified code, do.call is used to explicitly pass the formulas as arguments to the lme function. The quote function is used to ensure that data_in is passed correctly.
Step 4: Modify the call to use new_data instead of data_in
When calling the predict function, you need to modify it to pass new_data instead of data_in. Here’s how:
make_prediction_nlm(data_in = fake_data_complicated_1,
y_var = "why",
x_var = "ecks",
treatment_var = "treatment",
id_var = "ID",
new_data = fake_data_complicated_1)
should be replaced with:
make_prediction_nlm(data_in = fake_data_complicated_1,
y_var = "why",
x_var = "ecks",
treatment_var = "treatment",
id_var = "ID")
This will ensure that the new_data argument is passed correctly to the predict function.
With these modifications, your code should work as expected.
Last modified on 2024-01-25