Home > Mobile >  Convert a string vector into a formula style, removing **""*
Convert a string vector into a formula style, removing **""*

Time:10-27

I want to convert the following string vector:

variables <- c("temperature", "rain", "sun_days", "season")

into the following formula:

formula <- pred ~ treatment*(temperature   rain   sun_days   season)

The way I converted the variables vector into a formula style is the following:

predictors <- paste0(variables, collapse = " ")

However, it does not make the trick when I write the formula in the following way:

formula <- pred ~ treatment*(variables)

It doesn't work because of the "" that characterises the string vector.

Any idea?

CodePudding user response:

formula <- as.formula(
  paste("pred ~ treatment * (", paste(variables, collapse = " "), ")")
)

Result:

> formula
pred ~ treatment * (temperature   rain   sun_days   season)
  • Related