rmodel.matrix

How to paste formula into model.matrix function in R?


By way of simplified example, say you have the following data:

n <- 10
df <- data.frame(x1 = rnorm(n, 3, 1), x2 = rnorm(n, 0, 1))

And you wish to create a model matrix of the following form:

model.matrix(~ df$x1 + df$x2)

or more preferably:

model.matrix(~ x1 + x2, data = df)

but instead by pasting the formula into model.matrix. I have experimented with the following but encounter errors with all of them:

form1 <- "df$x1 + df$x2"
model.matrix(~ as.formula(form1))
model.matrix(~ eval(parse(text = form1)))
model.matrix(~ paste(form1))
model.matrix(~ form1)

I've also tried the same with the more preferable structure:

form2 <- "x1 + x2, data = df"

Is there a direct solution to this problem? Or is the model.matrix function not conducive to this approach?


Solution

  • Do you mean something like this?

    expr <- "~ x1 + x2"
    model.matrix(as.formula(expr), df)
    

    You need to give df as the data argument outside of as.formula, as the data argument defines the environment within which to evaluate the formula.

    If you don't want to specify the data argument you can do

    model.matrix(as.formula("~ df$x1 + df$x2"))