Scott
Scott

Reputation: 295

Using a function parameter and passing it in to lm formula

I am trying to create a function that passes a parameter in as the dependent variable with the independent variables staying the same.

I have tried to use {{}} but see the problem as something like the below if select contains was possible.

test_func <- function(dataframe, dependent){
  model <- tidy(lm({{ dependent }} ~ . - select(contains("x")), data = dataframe))

  return(model)
}

test_func(datasets::anscombe, x1)

The function should pass as function(dataframe, dependent) with a single model.

Upvotes: 1

Views: 305

Answers (1)

jay.sf
jay.sf

Reputation: 72683

Use reformulate().

f <- function(d, y) lm(reformulate(names(d)[grep("x", names(d))], response=y), data=d)

f(datasets::anscombe, "y1")
# Call:
#   lm(formula = reformulate(names(d)[grep("x", names(d))], response = y), 
#      data = d)
# 
# Coefficients:
#   (Intercept)           x1           x2           x3           x4  
#       4.33291      0.45073           NA           NA     -0.09873  

Upvotes: 1

Related Questions