I decided to try my hand writing a simple custom function doing a t-test on some lm()
-produced regression's estimators (for example, H_0: Beta_j = "some constant" vs H_1: Beta_j < "some constant").
This is my first time creating my own code, but I have been working with R for a few months and I think I have a decent understanding of it, so I do not understand why I keep getting a "subscript out of bounds" on running it.
My code:
custom_test<-function(data,coeff,alt,alternative=c("two.sided","greater","less"),clevel=.95){
dof<-data$df.residual
top<-data$coefficients["coeff"]-alt
bottom=coef(summary(data))["coeff","Std. Error"]
stat<-abs(top/bottom)
if (alternative=="two.sided") {
tstat<-qt(clevel/2,dof)
pstat<-2*pt(tstat,dof)
return(pstat)
} else if (alternative=="greater") {
tstat<-qt(clevel/2,dof)
pstat<-pt(tstat,dof)
return(pstat)
} else if (alternative=="less") {
tstat<-qt(clevel/2,dof)
pstat<-pt(tstat,dof)
return(pstat)
} else {
return("Error")
}
}
And I try to run this with standard lm()
results, hrsemp
being a var., and get the error:
custom_test(fit9,hrsemp,0,alternative="less")
Error in coef(summary(data))["coeff", "Std. Error"] :
subscript out of bounds
But everytime I run the problematic code manually myself, I do get an answer:
> coef(fit9)
(Intercept) hrsemp log(sales) log(employ)
12.45837237 -0.02926893 -0.96202698 0.76147045
> coef(summary(fit9))["hrsemp", "Std. Error"]
[1] 0.02280484
Other Stack Exchange questions regarding this error all seem to be subtly different, and I haven't been able to generalize their lessons to my code thus far.
Where am I going wrong?