0
我有一个名为bjmd
数据集,看起来像这样(简化):如何在变量内重复循环?
rte year y obs
22037 46001 1 0 1
22042 46001 2 4 3
22047 46001 3 5 3
22202 46002 1 11 1
22207 46002 2 14 1
22212 46002 3 6 1
22140 46003 1 5 6
22141 46003 2 2 6
22142 46003 3 6 6
我想运行一个循环来为每个不同的rte
(46001,46002,46003)进行glm
分析。在每个rte
内,有多个year
s,它们全都需要包含在glm
分析中。从每条路线的glm
测试中,我将采用坡度并创建另一个路线和坡度作为列的表格。这是我希望它看起来像:
rte slope
46001 x
46002 y
46003 z
下面是循环代码我想出了:因为我一直得到0值我斜率
route<-with(bjmd,unique(rte))
slope<-with(bjmd,numeric(length(unique(rte))))
table<-data.frame(route,slope)
for (i in unique(as.factor(bjmd$rte))) {
data<-subset(bjmd, rte=='i')
slope[i] <- coef(summary(glm(y ~ year+obs,
family = poisson(link=log),data=data)))[2,1]
table[i,2] <-paste(slope[i])
})
table
东西是不对的代码:
route slope
1 46001 0
2 46002 0
3 46003 0
有人可以帮指出哪里我搞乱它呢?
您需要从'data <-subset(bjmd,rte =='i')''周围移除'i'的引号。目前,您正在对与字符串“i”相等的值进行子集化。 – Thomas 2013-07-06 14:42:49