Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")
b <- c(TRUE, FALSE, FALSE)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use ifelse and reformulate

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

var0 ~ factor(var1) + var2 + var3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading