Several cycles for a cycle

I have an R data frame greatly simplified as:

id <- rep(1:2, c(6,8)) correct <- sample(0:1,14,TRUE) phase <- c(rep("discr",3),rep("rev",3), rep("discr",4),rep("rev",4)) dat <- data.frame(id,correct,phase) 

with id as my subjects (in reality I have a lot more than 2), correct = answers encoded as incorrect (0) or correct (1), and phases Discrimination and Reversal (inside the subject).

I want to perform a logical regression as

 glm(correct~phase, dat, family="binomial") 

additional predictors may be added later. However, since I have a different amount of data for each object, I would like to execute glm() separately for each object, and then compare the coefficients with ANOVA for group effects. I would like to do this in a for loop as

 for(i in seq_along(dat$id)){ my_glm[i] <- glm(correct~list,dat[dat$id==i,],family="binomial") } 

but keep getting the error message

 >Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels. 

I checked my data and there is no factor that contains only one level. All subjects gave at least one incorrect and one correct answer, and all took part in Discrimination and Recovery. This function works outside the loop when I specify a specific object.

+4
source share
2 answers

you are currently trying to do glm for each line in id :

I think you want glm for each id separately. Personally, I would go with something like:

 library(plyr) ddply(dat, .(id), function (x){ intercept <- coef(summary(glm(correct~phase,family="binomial",data=x)))[1] slope <- coef(summary(glm(correct~phase,family="binomial",data=x)))[2] c(intercept,slope) }) # id V1 V2 #1 1 -0.6931472 1.386294e+00 #2 2 1.0986123 -6.345448e-16 # here V1 is intercept and V2 is the estimate 
+4
source

Here R is the base solution:

 > lapply(split(dat, dat$id), function(x) coef(summary(glm(correct~phase,family="binomial",data=x)))) $`1` Estimate Std. Error z value Pr(>|z|) (Intercept) -6.931472e-01 1.224745 -5.659524e-01 0.5714261 phaserev -3.845925e-16 1.732050 -2.220446e-16 1.0000000 $`2` Estimate Std. Error z value Pr(>|z|) (Intercept) 3.356998e-16 1.000000 3.356998e-16 1.000000 phaserev 1.098612e+00 1.527524 7.192109e-01 0.472011 
+4
source

All Articles