I have some data like this:
dat = tibble(
var1 = rep(c('A','B'),each=5)
, var2 = rnorm(10)
, var3 = rnorm(10)
, var4 = rnorm(10)
, var5 = rnorm(10)
)
I can get what I want by explicitly naming the columns to be used in the lm formula:
dat %>%
#dat has columns: var1 through var5
dplyr::group_by(var1) %>%
dplyr::mutate(
resids = resid(lm( var2 ~ var3 + var4 ))
)
But I actually have many columns in my real data set, and the number and names of the ones I'll be using will vary. I do know the names of the ones I don't want, so I thought this would work:
dat %>%
#dat has columns: var1 through var5
dplyr::group_by(var1) %>%
dplyr::mutate(
resids = resid(lm(
formula = var2 ~ .
, data = . %>% select(-var1, -var5)
))
)
But that doesn't seem to work. Any suggestions?