[英]Extract degrees of freedom in R
I am running a large number of linear regressions, and for each regression I would like to save the adjusted R squared and the degrees of freedom each in a seperate file. 我正在运行大量的线性回归,对于每个回归,我想将调整后的R平方和自由度分别保存在单独的文件中。
The code below does this perfectly for the adjusted R squared, and I can add the value name of the list to the file (so I can identify to which subset of mydata the R squared belongs). 下面的代码对于调整后的R平方完美地做到了这一点,我可以将列表的值名称添加到文件中(这样我就可以确定R平方属于mydata的哪个子集)。 In sum, it gives me 1 column with the list value, and 1 column with the R². 总之,它为我提供了带有列表值的一列和带有R²的一列。
For the degrees of freedom, R gives a 3-vector (p, np, p*) by default. 对于自由度,默认情况下R给出3向量(p,np,p *)。 Adding the row.name=i statement does not work here. 在此处无法添加row.name = i语句。 I would only need np. 我只需要np。 Is there a way to save the middle figure from the vector only and add the row name to the saved file? 有没有办法只保存矢量中的中间图形并将行名添加到保存的文件中?
I created a reproducible example below: 我在下面创建了一个可复制的示例:
Fictive dataset (mydata) 虚拟数据集(mydata)
v1 v2 v3
4 9 1
5 78 1
6 11 1
8 12 2
10 13 2
11 65 2
15 34 2
Code: 码:
list<-unique(mydata$v3)
for (i in 1:length(list)){
newdata <- mydata[ which(mydata$v3==i),]
reg <- lm((v1~v2), data=newdata)
write.table(summary(reg)$adj.r.square, file="rsquared.txt", append=TRUE, col.names = F, row.names=i)
write.table(summary(reg)$df, file="degreesoffreedom.txt", append=TRUE, col.names = F)
rm(reg)
rm(newdata)
}
What I currently get for the file "degreesoffreedom.tx" 我目前从文件“ degreesoffreedom.tx”获得的内容
"1" 2
"2" 1
"3" 2
"1" 2
"2" 2
"3" 2
What I need is: 我需要的是:
"1" 1
"2" 2
Try summary(reg)$df[2]
instead of summary(reg)$df
. 尝试summary(reg)$df[2]
而不是summary(reg)$df
。 Remember everything in R is an object and you can take a subset of any object. 请记住,R中的所有内容都是一个对象,您可以获取任何对象的子集。
Second solution reg$df
. 第二个解决方案reg$df
。 You'll only get three different DF when you wrap summary
around your regression. 将summary
包装在回归周围时,只会得到三个不同的DF。
The call to which
is unnecessary, ie newdata <- mydata[mydata$v3==i,]
. 该呼叫which
是不必要的,即newdata <- mydata[mydata$v3==i,]
。 In my experience, 99% of the time you think you need which
you don't. 根据我的经验,有99%的时间您认为自己不需要which
而不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.