How does one convert a vector of variable names into a formula in R while allowing the user to specify some as factors?

Say I have a pair of vectors, one consisting of variable names and the other containing Booleans that determine whether the variables in the first vector should be treated as factors or not:

a <- c("var1", "var2", "var3")

Is there a way of automatically converting these two vectors into a formula of the form:

var0 ~ factor(var1) + var2 + var3

? If you have a technique of doing this that doesn’t work with a second vector of Booleans, but requires some other way of specifying which variables are to be treated as factors, I’m still happy to hear your technique.

>Solution :

You could use ifelse and reformulate

reformulate(ifelse(b, sprintf("factor(%s)",a), a), 'var0')

var0 ~ factor(var1) + var2 + var3

Leave a Reply