'fitting a logistic regression model in R

    rotenone <- data.frame(dose=factor(c("high", "medium", "low")),
                       affected=c(44, 24, 0),
                       total=c(50, 46, 49))
    print(rotenone)

     dose affected total
 ##1   high       44    50
 ##2 medium       24    46
 ##3    low        0    49



    rotenone_logit_mod <- glm(affected ~ 1 + dose, data = rotenone, family = binomial(link = "logit"))
    summary(rotenone_logit_mod)

above is my code for comparing the proportion of affected insects in the three groups by fitting a logistic regression model.

but the error is: "Error in eval(family$initialize) : y values must be 0 <= y <= 1"

can someone please help me fix the problem? thank you



Solution 1:[1]

The problem is your dataframe, which can't look like this:

rotenone <- data.frame(dose=factor(c("high", "medium", "low")),
                       affected=c(44, 24, 0),
                       total=c(50, 46, 49))

If you want to fit a logistic regression model you have to modify your data: the outcome variable has to be a binary one (0 for not affected and 1 for affected). If you are not familiar with dplyr you could do it like that:

rotenone %<>% mutate(not_affected = total-affected, .after = affected)
df_affected <- data.frame(dose = rep(rotenone$dose, 
                                     times = rotenone$affected),
                          affected = 1)
df_not_affd <- data.frame(dose = rep(rotenone$dose, 
                                     times = rotenone$not_affected),
                          affected = 0)
rotenone_mod <- rbind.data.frame(df_affected, df_not_affd)

Look at the summary of your new dataframe, it should match the values of your old one:

summary(rotenone_mod)

That is the case, so now you can fit your model:

rotenone_logit_mod <- glm(affected ~ 1 + dose, 
                          data = rotenone_mod, 
                          family = binomial(link = "logit"))
summary(rotenone_logit_mod)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J-WoW