predict的用法:
predict(object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
interval = c("none", "confidence", "prediction"),
level = 0.95, type = c("response", "terms"),
terms = NULL, na.action = na.pass,
pred.var = res.var/weights, weights = 1, ...)
只要注意其中的object,newdata,interval,level,type就行。
object是你的回归模型。
newdata是使用的数据。
interval选confidence或者"c"。
level是置信水平。
type在计算响应变量时使用response,对变量计算使用terms。如果是terms,需要用后面的terms参数指定变量名(character类型向量形式)。
response的话返回一个数据框,三列,分别是预测值,区间下限和上限。
terms返回一个list。
用R语言求置信区间是很方便的,而且很灵活,至少我觉得比spss好多了。如果你要求的只是95%的置信度的话,那么用一个很简单的命令就可以实现了
首先,输入da=c(你的数据,用英文逗号分割),然后t.test(da),运行就能得到结果了。
我的数据是newbomb <- c(28,26,33,24,34,-44,27,16,40,-2,29,22,24,21,25,30,23,29,31,19)
t.test(newbomb)得到的结果如下
如果要求任意置信度下的置信区间的话,就需要自己编一个函数了。
当然,有两点要记住的,置信区间的计算在知道方差和不知道方差的情况下,计算公式是不一样的。
下面做一个两种情况下都可以用的函数。
confint<-function(x,sigma=-1,alpha=0.05)
{
n<-length(x)
xb<-mean(x)
if(sigma>=0)
{
tmp<-sigma/sqrt(n)*qnorm(1-alpha/2)df<-n
}
else{
tmp<-sd(x)/sqrt(n)*qt(1-alpha/2,n-1)df<- n-1
}
data.frame(mean=xb,df=df,a=xb-tmp,b=xb+tmp)
}
这个函数的使用:
如果不知道方差,则confint(x,alpha) 知道方差,则confint(x,sigma,alpha)
这样就能计算出结果了。
用predict就能做到。
predict的用法:
predict(object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
interval = c("none", "confidence", "prediction"),
level = 0.95, type = c("response", "terms"),
terms = NULL, na.action = na.pass,
pred.var = res.var/weights, weights = 1, ...)
object是你的回归模型。
newdata是使用的数据。
interval选confidence或者"c"。
level是置信水平。
type在计算响应变量时使用response,对变量计算使用terms。如果是terms,需要用后面terms参数指定变量名(character类型向量形式)。