Why my " Y~." equation doesn't recognize any variables when using list() function?

Could you provide a reproducible example, and the error message that you get?

From your code, I suspect the problem is your use of .(1,2), what is the (1,2) supposed to be? When defining a formula, . is a shorthand to mean "all other variables", but typically it's not itself a function or operator.

So, using mtcars and lm() for a reproducible example:

form1 <- mpg ~ .

lm(form1, data = mtcars)
#> 
#> Call:
#> lm(formula = form1, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)          cyl         disp           hp         drat           wt  
#>    12.30337     -0.11144      0.01334     -0.02148      0.78711     -3.71530  
#>        qsec           vs           am         gear         carb  
#>     0.82104      0.31776      2.52023      0.65541     -0.19942

form2 <- mpg ~ .(1,2)

lm(form2, data = mtcars)
#> Error in .(1, 2): could not find function "."

The first one automatically replaces . with all variables, the second one is an error.

If your goal is to use all but a few variables (and you've been using (1,2) to try to subset them), you can use a more explicit approach:

vars_present <- names(mtcars)

vars_present
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
#> [11] "carb"

vars_to_keep <- vars_present[-(1:3)]

vars_to_keep
#> [1] "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
vars_to_keep_text <- paste(vars_to_keep, collapse = " + ")

form3 <- as.formula(paste("mpg", "~", vars_to_keep_text))

form3
#> mpg ~ hp + drat + wt + qsec + vs + am + gear + carb

lm(form3, data = mtcars)
#> 
#> Call:
#> lm(formula = form3, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)           hp         drat           wt         qsec           vs  
#>    13.80810     -0.01225      0.88894     -2.60968      0.63983      0.08786  
#>          am         gear         carb  
#>     2.42418      0.69390     -0.61286

Created on 2025-03-12 with reprex v2.1.0

2 Likes