I’m probably doing something very silly but I can’t extract the parameter values from a series of models my function is looping through.
Data:
library(difR)
data(verbal)
TotScore=rowSums(verbal[,c(1:24)])
mydata=verbal[,c(1:24)]
I can then get the model BIC in a loop
library(BMA)
a<-rep(NA,length(1:24))
for (i in (1:24)){
a[i]<-bic.glm(mydata[,i]~ TotScore, glm.family=binomial,data=mydata)$bic
}
a
But if I try to put this in a function I can’t extract “a”
myB<-function(mydata){
a<-rep(NA,length(ncol(mydata)))
for (i in (1:ncol(mydata))){
a[i]<-bic.glm(mydata[,i]~ TotScore, glm.family=binomial,data=mydata)$bic
}
return(a)
}
myB(mydata)
Or rather the bic is only for the very last model
I can build the same function for the mean and manage to extract the results so maybe it’s something to do with the structure of the bic output?
Many thanks
M
It seems as though
bic.glmonly reads objects from the global environment – the problem with your function was that it did recognize theicreated locally within the function. Try the following:Your function was still reading the global
icreated by the first loop, which was at 24.It seems very strange that it should do this; after a quick google search I found references to the problem here and here (it wasn’t a very thorough search and I’m sure there are better examples). I couldn’t find anything in the documentation for
bic.glm, which is a bit surprising.From the first answer to the second link I provided, it seems like this would happen if you use a formula but do not specify a
dataparameter.