user17144
user17144

Reputation: 438

Contrasts can be applied to factors with 2 or more levels error in lm

When I run the two statements below in R to regress a against b and c, I get the error that I have pasted right below. All of the predictors have more than 2 levels. I am not sure what is wrong. Can somebody help?

d<-data.frame(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9))
 lmmod <- lm(colnames(d)[1] ~  paste(colnames(d)[2:length(colnames(d))], collapse = "+") , data = d[1:(nrow(d)),])


Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels
In addition: Warning message:
In storage.mode(v) <- "double" : NAs introduced by coercion

Upvotes: 0

Views: 1103

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

We can use reformulate

lm(reformulate(paste0(names(d)[-1], collapse = "+"), names(d)[1]), d)

Or using paste0

lm(paste0(names(d[1]),"~", paste0(names(d)[-1], collapse = "+")), d)

Upvotes: 1

Related Questions