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 to loop over string variable in R

How to use the names in the string vector in models? for example why cant I do this

loop_variables = c("Age", "BMI", "Height")

for (i in 1:length(loop_variables){
    basic_logistic_model = glm(outcome~loop_variable[i], data=DB, family="binomial"
    summary(basic_logistic_model)
}

I see alot of R users doing vectors with names of study variables then looping it
what am I doing wrong?

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 :

It is the formula that needs to be update. We may use paste or reformulate. In addition, it is better to have an object to store the output of summary especially a list would suit.

summary_lst <- vector('list', length(loop_variables))
names(summary_lst) <- loop_variables
for (i in 1:length(loop_variables){
    # convert the column to factor column
    DB[[loop_variables[i]]] <- factor(DB[[loop_variables[i]]])
    # create the formula
    fmla <- reformulate(loop_variable[i], response = 'outcome')
    basic_logistic_model = glm(fmla, data=DB, family="binomial")
    # assign the summary output to the list element
    summary_lst[[i]] <- summary(basic_logistic_model)
}
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