Home > Blockchain >  Error when plotting Linear regression - attempt to select less than one element in integerOneIndex
Error when plotting Linear regression - attempt to select less than one element in integerOneIndex

Time:11-01

here is the code:-

A<- as.factor(Fire)
X <- as.numeric(Length_in_meter)
No_of_parrots <- as.numeric(No_of_parrots)

model <- aov(No_of_parrots ~ X*A)
summary(model)


par(cex=1.5)
plot(X, No_of_parrots, type = "n" , las=1,
     xlab = "Length in meter" , ylab = "No_of_parrots")
SA <- split(X , A)
SY <- split(No_of_parrots , A)
for (i in 1:nlevels(A)) points(SA[[i]], SY[[i]], pch = i-1)
for (i in 1:nlevels(No_of_parrots)) abline(lm(SY[[i]] ~ SA[[i]]),  lty=1 )

then I got this output:

Error in SY[[i]] : 
  attempt to select less than one element in integerOneIndex

R plotted a graph with only one regression line, but there is suppose to have two. Can you please help when I have done wrong? Thanks,

CodePudding user response:

tl;dr for (i in 1:nlevels(No_of_parrots)) is probably a typo; you probably meant for (i in 1:nlevels(A)).

nlevels() is only relevant for factor variables. By using as.numeric(), you made sure that it was not a factor (even if it started out as one), hence nlevels() will return 0, e.g.

parrots <- factor(1:3)
nlevels(as.numeric(parrots))  ## 0

When you run a loop over 1:nlevels(...), this evaluates to 1:0c(1, 0) (this is one reason that seq(n) is generally recommended over 1:n). The first time through the loop you select the first elements of SA and SY. The second time through (i==0) you try to select the zeroth elements, which throws the error (I get a slightly different error, "attempt to select less than one element in get1index ", but that may be due to a different R version or something — the concept is the same).

  • Related