【发布时间】:2013-09-30 20:39:07
【问题描述】:
我正在尝试在 data.table 中执行一些 glm,以生成按关键因素拆分的建模结果。
我已经成功地做到了:
-
高级glm
glm(modellingDF,formula=Outcome~IntCol + DecCol,family=binomial(link=logit))
-
具有单列的作用域 glm
modellingDF[,list(结果, 拟合=glm(x,formula=Outcome~IntCol ,family=binomial(link=logit))$fitted), by=变量]
-
具有两个整数列的范围 glm
modellingDF[,list(结果, 拟合=glm(x,formula=Outcome~IntCol + IntCol2 ,family=binomial(link=logit))$fitted ), by=变量]
但是,当我尝试使用十进制列在范围内执行高级 glm 时,会产生此错误
Error in model.frame.default(formula = Outcome ~ IntCol + DecCol, data = x, :
variable lengths differ (found for 'DecCol')
我认为这可能是由于分区的长度可变,所以我用一个可重现的示例进行了测试:
library("data.table")
testing<-data.table(letters=sample(rep(LETTERS,5000),5000),
letters2=sample(rep(LETTERS[1:5],10000),5000),
cont.var=rnorm(5000),
cont.var2=round(rnorm(5000)*1000,0),
outcome=rbinom(5000,1,0.8)
,key="letters")
testing.glm<-testing[,list(outcome,
fitted=glm(x,formula=outcome~cont.var+cont.var2,family=binomial(link=logit))$fitted)
),by=list(letters)]
但这并没有错误。我认为可能是由于 NA 或其他原因,但 data.table modellingDF 的摘要没有表明应该有任何问题:
DecCol
Min. :0.0416
1st Qu.:0.6122
Median :0.7220
Mean :0.6794
3rd Qu.:0.7840
Max. :0.9495
nrow(modellingDF[is.na(DecCol),]) # results in 0
modellingDF[,list(len=.N,DecCollen=length(DecCol),IntCollen=length
(IntCol ),Outcomelen=length(Outcome)),by=Bracket]
Bracket len DecCollen IntCollen Outcomelen
1: 3-6 39184 39184 39184 39184
2: 1-2 19909 19909 19909 19909
3: 0 9912 9912 9912 9912
也许我今天打瞌睡,但有人可以提出解决方案或进一步深入研究此问题的方法吗?
【问题讨论】:
-
我考虑过,但
sapply(modellingDF, function(x) all(is.na(x)))每列都返回 FALSE -
你能做一个产生错误的可重现的例子吗?你已经展示了错误是好的,但不是产生它的原因,iiuc。
-
我只是想为您添加一个带有一些 dput 结果的可重现示例,并注意到一些相当奇怪的情况 - 当我将列名更改为远离实际工作的实际列名时。
modellingDF[sample(1:nrow(modellingDF),200),list(IntCol=Age,IntCol2=Score,Outcome,abc=LTV),key=Bracket]有效,但modellingDF[sample(1:nrow(modellingDF),200),list(IntCol=Age,IntCol2=Score,Outcome,LTV),key=Bracket]不会。我想也许我有一个名为 LTV 的变量,但没有,而且 data.table 应该优先考虑内部变量 -
在您的示例中,
x是什么? (即glm(x, formula = ...)。通常您需要引用.SD作为data参数才能使用正确的环境。
标签: r data.table glm