rmumin

How to use R to convert a list of names into an equation for Dredge


I want to automate turning lists of names into regression equations for use in the Dredge command from the MuMIn package.

Making this:

[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"  

into this:

globalmodel <- lm(Sepal.Length ~ Petal.Length + Petal.Width + Species, data = iris,na.action = "na.fail")

Theoretically, seems simple--bunch of paste0. All I need is a way to automate the 'find-replace' of turning " " into +.

Why this madness? I keep adding variables/columns to my data table, and then needing to alter the dredge equation. Also, doing this would provide me with a dredge snippet that I could cross-apply to many different future dredges.


Solution

  • You could use reformulate to construct the formula

    reformulate(names(iris)[-1], names(iris)[1])
    #Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
    

    and use it in lm

    lm(reformulate(names(iris)[-1],names(iris)[1]),data = iris, na.action = "na.fail")