formula - R: how to pass in a reference to the variable in glm or lm? -
so let's have named vector:
sorted = c(1,2,3) names(sorted) = c("a","b","c")
and it'll following:
> sorted b c 1 2 3
so vector named a,b,c, , has value 1,2,3 respectively.
and have sample data:
data.ex = as.data.frame(matrix(rep(c(1,2,3,4),3), nrow = 3, ncol = 3)) colnames(data.ex) = c("a","b","c")
so data frame has 3 columns named a,b,c well.
i want predict c using value in glm():
fit.ex = glm(formula = c ~ names(sorted)[2], data = data.ex, family = binomial(link = "logit"))
but then, i'll keep getting following error message:
error in model.frame.default(formula = c ~ names(sorted)[2], data = data.ex,: variable lengths differ (found 'names(sorted)[2]')
i read article here , found as.name() function, still not working: http://www.ats.ucla.edu/stat/r/pages/looping_strings.htm
and cannot find else thats similar problem. please, if there thread addressing problem, guide me it! or kind of appreciated! :)
providing answer based on comments:
sorted = c(a=1,b=2,c=3) names(sorted) = c("a","b","c") data.ex = data.frame(a=1:4,b=2:5,c=c(1,0,0,1))
construct list of formulas:
forms <- lapply(names(sorted)[1:2],reformulate,response="c") models <- lapply(forms,glm,data = data.ex, family = binomial(link = "logit"))
then can things like
t(sapply(models,coef))
the plyr
package handy sort of thing (e.g. plyr::ldply(models,coef)
)
Comments
Post a Comment