> beta.int<-function(fm,alpha=0.05){ + A<-summary(fm)$coefficients + df<-fm$df.residual + left<-A[,1]-A[,2]*qt(1-alpha/2, df) + right<-A[,1]+A[,2]*qt(1-alpha/2, df) + rowname<-dimnames(A)[[1]] + colname<-c("Estimate", "Left", "Right") + matrix(c(A[,1], left, right), ncol=3, + dimnames = list(rowname, colname )) + }
运用①:
> x<-c(0.10, 0.11, 0.12, 0.13, 0.14, 0.15, + 0.16, 0.17, 0.18, 0.20, 0.21, 0.23) > y<-c(42.0, 43.5, 45.0, 45.5, 45.0, 47.5, + 49.0, 53.0, 50.0, 55.0, 55.0, 60.0)
> lm.sol<-lm(y ~ 1+x) > fm=lm.sol
> A<-summary(fm)$coefficients #通过summary()获取系数
> A[,1] #estimate (Intercept) x 28.49282 130.83483
> A[,2] #std.error (Intercept) x 1.579806 9.683379
> alpha=0.05 > 1-alpha/2 [1] 0.975
> df<-fm$df.residual #通过回归方程lm()获取残差自由度 > df #df=n-2(变量个数) [1] 10
> qt(1-alpha/2, df) [1] 2.228139
> A[,2]*qt(1-alpha/2, df) #标准差*分布函数的反函数(即给定概率的t检验下分位点) (Intercept) x 3.520027 21.575913
> left<-A[,1]-A[,2]*qt(1-alpha/2, df) #区间左侧值 预测值减去标准差与下分位点的乘积 > right<-A[,1]+A[,2]*qt(1-alpha/2, df) #区间左侧值 预测值加上标准差与下分位点的乘积
> dimnames(A) [[1]] [1] "(Intercept)" "x"
[[2]] [1] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
> dimnames(A)[[1]] [1] "(Intercept)" "x"
> A[[1]] [1] 28.49282 > A[1] #效果一样,都是(1,1) [1] 28.49282
> dimnames(A)[[1]] [1] "(Intercept)" "x" > dimnames(A)[1] #效果不一样,选择第一组 [[1]] [1] "(Intercept)" "x"
> dimnames(A)[2] #选择第二组 [[1]] [1] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
> rowname<-dimnames(A)[[1]] > colname<-c("Estimate", "Left", "Right")
> c(A[,1], left, right) (Intercept) x (Intercept) x (Intercept) x 28.49282 130.83483 24.97279 109.25892 32.01285 152.41074
> matrix(c(A[,1], left, right), ncol=3, + dimnames = list(rowname, colname )) Estimate Left Right (Intercept) 28.49282 24.97279 32.01285 x 130.83483 109.25892 152.41074