0

I'm trying to apply a lapply for doing a regression, but I get an error:

A reproducible example

set.seed(42)  
n <- 6
juntar_blocs <- data.frame(id=1:n, 
                           pond_total_index_blocs_iguals = sample(1:n),
                           unitatespecifica = sample(0:1,n, replace = TRUE),
                           responsable = sample(0:1,n, replace = TRUE),
                           actu_transv=  sample(0:1,n, replace = TRUE),
                           util_rec_nuevo_pers = sample(0:1,n, replace = TRUE),
                           ord_aprob = sample(0:1,n, replace = TRUE), 
                           pers_transp_tareas = sample(0:1, n, replace = TRUE), 
                           util_rec_nuevo_pers = sample(0:1, n, replace = TRUE))


My code:

objects for dependent and independent variables

dep<-list("pond_total_index_blocs_iguals") 
variables_index_subst_ <- c("unitatespecifica", "responsable", "actutransv", "util_rec_nuevo_pers", "ord_aprob", "pers_transp_tareas", "util_rec_nuevo_pers")

The database is called juntar_blocs. Then I write the code

models <- lapply(dep, function(x, y)
    step(lm(as.formula(paste(x, paste(y, collapse="+"))), data=juntar_blocs), 
         direction="backward"), y = variables_index_subst_)

I get this error

Error in str2lang(x) : <text>:1:31: unexpected symbol
1: pond_total_index_blocs_iguals unitatespecifica

Thank you!

                              ^
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. You are `lapply`-ing over just one variable so the function you provide should just have an `x` and not a `y` parameter. But your code to create the formula looks wrong. There should be a `~` in there if it's a proper formula. You seem to just have an extra space so your formula is not syntactically valid – MrFlick May 30 '23 at 18:38
  • Thank you @MrFlick I just wrote a reproducible example – FrancoBattiato May 30 '23 at 20:21

1 Answers1

1

Here is a very similar problem with an explanation as to the error. When using sapply,I get Error in str2lang(x) : <text>:1:31: unexpected symbol 1 ^

The solution is similar in the addition of the tilde, as MrFlick already noted. You also have a discrepancy in your example between "actu_transv" and "actutransv" that will throw an error. Note that this solution leads to a different error based on your sample data. It says that step can't be performed because AIC is -infinity. But this solves the question you asked.

models <- lapply(dep, function(x, y)
  step(lm(as.formula(paste(x,"~", paste(y, collapse="+"))), data=juntar_blocs), 
       direction="backward"), y = variables_index_subst_)
stomper
  • 1,252
  • 1
  • 7
  • 12