Passing Assigned Value into Formula

I'm trying to pass an assigned value into a formula for a recipe and have not found a way to have it's syntax recognized. Here's a reprex:

library(tidymodels)

t <- "Target" # I would like to assign the column to target, i.e. dependent variable

Target <- as.factor(sample(c("A", "B"), 100, replace = TRUE))
Other <- as.factor(sample(c("AA", "BB", "CCC", "DDD"), 100, replace = TRUE))
Numb1 <- sample(1:100, 100, replace = TRUE)
Numb2 <- sample(1:100, 100, replace = TRUE)
df <- tibble(Target, Other, Numb1, Numb2)

"Target is the name of column I'd like to use in the formula, however, when it gets assigned to 't' I get an error Error in model.frame.default(formula, data[1, ]) : object is not a matrix.

rec <- recipe(t ~., data = df) %>%
step_center_to(all_numeric_predictors(), skip = F)

If I attempt to subset this

t1 <- df[,t]

rec <- recipe(t1 ~., data = df) %>%
step_center_to(all_numeric_predictors(), skip = F)

Results in Error in model.frame.default(formula, data[1, ]) :invalid type (list) for variable 't1'

If I simply type in Target in the formula this works, but does not work for my use case when the target is dynamic and assigned prior:

rec <- recipe(Target ~., data = df) %>%
step_center_to(all_numeric_predictors(), skip = F)

How can I get an assigned value to work in a formula?

library(tidymodels)
library(sparseR)
library(glue)
t <- "Target" # I would like to assign the column to target, i.e. dependent variable

Target <- as.factor(sample(c("A", "B"), 100, replace = TRUE))
Other <- as.factor(sample(c("AA", "BB", "CCC", "DDD"), 100, replace = TRUE))
Numb1 <- sample(1:100, 100, replace = TRUE)
Numb2 <- sample(1:100, 100, replace = TRUE)
df <- tibble(Target, Other, Numb1, Numb2)

rec <- recipe(as.formula(glue("{t} ~.")), data = df) %>%
step_center_to(all_numeric_predictors(), skip = F)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.