3

I have to add approximately 30 dummy variables to a regression.

If my variables would be named dummy1 - dummy30, I would denote this with an asterisk wildcard in STATA. It would be simply regress y dummy* and STATA would add all variables starting with 'dummy'.

Can anyone hint me to a similar convenient procedure in [R] which prevents me from writing out 30 variable names?

5
  • y ~ ., data = <a data.frame with only the columns you want to include in your regression, where you can use a regular expression for subsetting>
    – Roland
    Sep 29, 2014 at 8:08
  • Thanks, but what if I would like it to more flexible? That is, I know a K amount of dummy variables in my data frame but they are scattered. I would have to specify the exact column numbers which is undesirable.
    – Raynor
    Sep 29, 2014 at 8:12
  • 2
    If you dummies encode a factor variable, you should be aware that R regression functions can do that for you.
    – Roland
    Sep 29, 2014 at 8:46
  • You can subset using regular expressions any variable you want (and then use the y ~ . formula). Sep 29, 2014 at 8:50
  • That's a good point, @Roland, letting R include my variable as a factor. If I remember correctly: as.factor().
    – Raynor
    Sep 29, 2014 at 8:59

2 Answers 2

4

You have two options. Either subset a data.frame to contain only dummy* variables and the dependent variable. In which case, you can call lm(dep ~ ., data = your.data). The dot argument will assume you're trying to use all but dep as predictors. To subset a data.frame of only dep and predictors, you can use your.data[grepl("dep|dummy", names(your.data)), ].

Second option is to construct a formula argument using paste.

formula(paste("dep ~", paste("dummy", 1:10, sep = "", collapse = "+")))
3

The function reformulate is the right option for creating formulas based on strings.

An example data frame:

set.seed(1)
dat <- data.frame(y = rnorm(10), 
                  dummy1 = rnorm(10),
                  dummy2 = rnorm(10),
                  dummy3 = rnorm(10),
                  other = rnorm(10))

Now, grep is used to find all dummy* variables. The result is used for the function reformulate:

form <- reformulate(grep("^dummy", names(dat), value = TRUE), response = "y")
# y ~ dummy1 + dummy2 + dummy3

This formula can be used for lm:

lm(form, dat)
# Call:
#   lm(formula = form, data = dat)
# 
# Coefficients:
#   (Intercept)       dummy1       dummy2       dummy3  
# 0.04785      0.09323     -0.63404     -0.19547

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.