Running lm() errror: Error in xj[i] : invalid subscript type 'list'

I keep getting this error and I don't understand what I am supposed to change

Here is the code I am using.

fit <- elsa12 %>%
   lm(formula = notact1~cesd2, data = elsa12)%>%
    filter(!is.na(notact1),!is.na(ncesd2))

Error in xj[i] : invalid subscript type 'list'.


Solution 1:

I think

fit <- (elsa12 
     %>% lm(formula = notact1~cesd2)
)

should work.

  • you don't need to specify data=elsa12 in the lm() call (the pipe automatically feeds elsa12 to lm() as the first unspecified argument, which in this case is data), and in fact this confuses R because it thinks you're specifying the next argument, which is subset — that is the proximal cause of your error ("invalid subscript type 'list'")
  • your filter should be unnecessary because lm() automatically drops cases that have NA in any of the model variables
  • even if you did want to use filter, it looks like it was in the wrong order (i.e. you should have used elsa12 %>% filter(...) %>% lm(...))