Search code examples
rstringdplyrformula

Convert a string vector into a formula style, removing **""*


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?


Solution

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

    Result:

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