循环中有多个glm [英] Multiple glm in for loop
问题描述
id < - rep(1:2,c(6 ,8))
$作为我的主题(实际上我有2个以上),
正确< - 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)
=编码为不正确(0)或正确(1)的响应,以及
id
>正确阶段
歧视和反转(受试者内因素)。
我想以
的形式进行逻辑回归, glm(正确的〜phase,dat,family =binomial)
稍后可能会增加额外的预测变量。
但是,由于每个科目的数据量都不相同,因此我希望对每个科目分别执行glm()
,然后将这些系数与ANOVA为团体效果。
我想这样做for循环的形式为
pre $for(i in seq_along(dat $ id)){
my_glm [i]< - glm(correct_list,dat [dat $ id == i,],family =binomial)
}
但不断收到错误讯息
>对比中的错误< -`(`* tmp *`,value = contr.funs [1 + isOF [nn]]):
对比度只能应用于2级或更多级的因子。
我检查了我的数据,没有包含一个级别的因素。所有的科目都至少给出了一个不正确的和一个正确的答案,都参与了歧视和反转。当我指定一个特定的主题时,该函数在循环之外工作。
您目前正在尝试为 glm
id
:
我想你想要 glm
每个 id
分别。 ,我会去这样的:
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(截距,斜率)
})
#id V1 V2
#1 1 -0.6931472 1.386294e + 00
#2 2 1.0986123 -6.345448e-16
#这里V1是截距,V2是估计
I have an R dataframe, strongly 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
= responses coded as incorrect (0) or correct (1), and the phases
Discrimination and Reversal (within-subjects factor).
I want to perform a logistic regression in the form of
glm(correct~phase, dat, family="binomial")
later possibly adding additional predictors.
However, since I have a varying amount of data for each subject, I would like to perform glm()
seperately for each subject and later compare the coefficients with ANOVA for group effects.
I would like to do this in a for loop in the form of
for(i in seq_along(dat$id)){
my_glm[i] <- glm(correct~list,dat[dat$id==i,],family="binomial")
}
but keep receiving 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 have checked my data and there is no factor which contains only one level. All subjects gave at least one incorrect and one correct response, and all took part in Discrimination and Reversal. The function works outside the loop when I specify a particular subject.
you currently trying to do a glm
for each row in of id
:
I think you want a glm
for each id
seperately. 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
这篇关于循环中有多个glm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!