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

Turn comma separated vector into list of predictors separated by +

I want to pass a comma separated vector i’ve manually created directly to a glm model. The model requires predictors to be separated by a plus sign + so I was wondering if there was a clever way to replace the ,s with +s as I pass the vectors to the model?

For example, say I have these two vectors:

fruits <- c('apples', 'bananas', 'pears', 'apricots')
colors <- c('blue', 'red', 'orange', 'purple')

At the moment, i’m just copying the predictors and adding in + signs manually. E.g.

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

glm(dependent_var ~ apples + bananas + pears + apricots + blue + red + orange + purple, data = df, family = "binomial")

What i’d love to do is find a way to make this less manual. E.g. is there a way I can basically just copy in the vector names themselves? Something like

glm(dependent_var ~ fruits + colors, data = df, family = "binomial")

>Solution :

1) Use reformulate:

#reformulate(c(fruits, colors), "dependent_var")
## dependent_var ~ apples + bananas + pears + apricots + blue + 
##     red + orange + purple

2) Another possibility is:

glm(dependent_var ~., data = df[c(fruits, colors)], family = "binomial")
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