'R: Prevent "~." in a linear mixed effect model from running an independent variable as both a fixed and random effect

I seem to be running into some issues when I run the code below:

library(lme4)

columns <- c("disp", "hp", "wt", "qsec", "vs")


X <- mtcars[,c(columns, 'cyl', 'carb', 'gear')] # data


rf <- lmer(cyl~ (carb | gear) +., data = X)

rf

### The output that I don't want (lists 'carb' and 'gear' as fixed variables):

Linear mixed model fit by REML ['lmerMod']
Formula: cyl ~ (carb | gear) + .
   Data: X
REML criterion at convergence: 76.9662
Random effects:
 Groups   Name        Std.Dev. Corr 
 gear     (Intercept) 0.2887        
          carb        0.2039   -1.00
 Residual             0.5202        
Number of obs: 32, groups:  gear, 3
Fixed Effects:
(Intercept)         carb         gear         disp           hp           wt  
  10.179140     0.025990    -0.873174     0.003883     0.008190     0.089656  
       qsec           vs  
  -0.159582    -0.779400  

As you can see, it is counting 'carb' and 'gear' as fixed variables when I only need them to be used for my random effect variable.

My goal is to keep the code in a similar format and also be able to run the model without the variables 'carb' and 'gear' being taken in as fixed effects (only as random effects).

How can I prevent "~." in the first model from selecting 'carb' and 'gear' as fixed variables so that it may produce the same output as the second model below?

The output that I need: (ONLY 'carb' and 'gear' listed as random effects):

> el <- lmer(cyl~ disp + hp + wt + qsec + vs + (carb | gear), data = mtcars)

> el

Linear mixed model fit by REML ['lmerMod']
Formula: cyl ~ disp + hp + wt + qsec + vs + (carb | gear)
   Data: mtcars
REML criterion at convergence: 79.7548
Random effects:
 Groups   Name        Std.Dev. Corr 
 gear     (Intercept) 0.9932        
          carb        0.1688   -0.82
 Residual             0.5263        
Number of obs: 32, groups:  gear, 3
Fixed Effects:
(Intercept)         disp           hp           wt         qsec           vs  
   6.848103     0.004024     0.006929     0.172789    -0.169145    -0.785878  

Any help at all is greatly appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source