Reputation: 351
I have a model object from a model (glm) that someone else built in R.
There are a couple of variables in the model that I would like to re-name. I don't have easy access to re-run their code and build the model with a different variable name in their data frame.
For example, they called a certain variable "previous_customer" and coded it as a dummy variable. But in the data frame I'm using, I have a categorical variable called "previous_customer" and the code we're running needs "previous_customer" to be a categorical variable in a few different places.
I could replace previous_customer everywhere in the code that I'm starting with, but I was hoping there was some way to just rename "previous_customer" in the model object I'm working with to something like "previous_customer_flag". If I could do that, it would take me about 2 seconds to handle this problem. However, I'm surprised that I'm not really finding anything on how to rename the variable once a model is built.
Does anyone know how to do this, or if it's not possible for some reason?
Upvotes: 3
Views: 2275
Reputation: 142
Came across this question when looking for an optimal fix myself.
I ended up using
names(model) <- sub("old_name", "new_name", names(model))
Upvotes: -1
Reputation: 5263
@AndrewGustar is right: your way can be done by replacing every instance of the variable name throughout the list. But those names appear in a lot of places, as both character vectors and language objects.
A simpler option would be to write a function wrapped around predict
which prepares the dataset's columns:
predict_with_rename <- function(object, newdata = NULL, ...) {
if (!is.null(newdata)) {
newdata[["previous_customer"]] <- newdata[["previous_customer_flag"]]
}
predict(object, newdata, ...)
}
Upvotes: 2