问题
I want to be able to define my target variable 'def_target' outside the regression code below:
model1 <- glm(def_target~., family=binomial(link='logit'),data=train70)
I have tried the following but get an error pop up
tv1 <- 'def_target'
model1 <- glm(tv1~., family=binomial(link='logit'),data=train70)
If anyone could help me that would be great.
Thanks
回答1:
I think it might tip up cause you tell it in your model1: glm(tv1~., family=binomial(link='logit'),data=train70). train70 does not have a matching column. Try to assign your variable directly, i.e.
tv1 <- train70[['def_target']]
then
model1 <- glm(tv1~., family=binomial(link='logit'))
I must admit I am not familiar with the "." you have in there. But make sure to relate that to your original dataset like you did with tv1.
回答2:
glm() requires the first argument to be of class "forumla", and simply inserting a string (i.e., 'def_target') will not parse correctly. You need to turn the argument into a formula by using as.formula(), but the entire formula you want to use must be included. Here's code that works:
model1 <- glm(as.formula(paste(tv1," ~ .")), family=binomial(link='logit'), data=train70)
来源:https://stackoverflow.com/questions/37364122/define-target-variable-in-glm-r