2

I'm trying to do something like the following:

control_set_1 = "education + income + sex + birth + race + trust_daily"
control_set_2 = "sex + birth + race + trust_daily"

fit_controls <- lm(data = data, dv ~ politics*treatment + control_set_1)
fit_controls_2 <- lm(data = data, dv ~ politics*treatment + control_set_2)

I have tried wrapping control_set_1 in as.formula(control_set_1), to no avail.

I get the error:

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data, : variable lengths differ (found for 'control_set_1')

What is the right way to do this?

Parseltongue
  • 11,157
  • 30
  • 95
  • 160

1 Answers1

5

The easiest workaround might be to avoid strings and just keep everything as a formula. Then you can use update() to change the formula as needed

control_set_1 = ~. + education + income + sex + birth + race + trust_daily
control_set_2 = ~. + sex + birth + race + trust_daily

fit_controls <- lm(data = data, update(dv ~ politics*treatment, control_set_1))
fit_controls_2 <- lm(data = data, update(dv ~ politics*treatment, control_set_2))

The . in the control_set formulas keep all existing predictors and just adds the new values in.

MrFlick
  • 195,160
  • 17
  • 277
  • 295