I met a problem. I calculate the odd.raio by using glm.
When the predictor outcomes were "A" and "B",respectively, the odd.ratio value is 0.88. However, outcome was "C" and "B", the odd.ratio value is 1.127948.
I don't know what the difference between "AB" and "BC" in the glm. the character can affect the results of odd.ratios which is right?
example code
outcome <- as.factor(c(rep("C",30),rep("B",28)))
#outcome <- as.factor(c(rep("A",30),rep("B",28)))
a <- c(seq(1,30,1),seq(1,28,1))
glm.log <- glm(outcome ~ scale(a), control = list(maxit = 50), family = binomial(link = "logit"))
res <- summary(glm.log)$coefficients[2, 1:2]
odd.ratio <- exp(res[1])
print(odd.ratio)
The odds ratio
show how the odds
change if we experience a change in the predictor (formula). Here is an example with a binary group variable since here the change is easy to understand.
# generate data and run model
outcome <- as.factor(c(rep("C",30),rep("B",30)))
groups<- c(c(rep(1, 20), rep(2, 10)),
c(rep(2, 20), rep(1, 10)))
fit <- glm(outcome ~ groups, family= binomial(link = "logit"))
odds.ratio <- exp(fit$coefficients["groups"])
# calculate odds by hand
tbl <- table(outcome, groups)
a <- tbl[1,1]
b <- tbl[1,2]
c <- tbl[2,1]
d <- tbl[2,2]
odds1 <- a/c
odds2 <- b/d
odds.ratio; odds1/odds2
# both 0.25
As you can see both, odds.ratio
from the model and our odds ratio odds1/odds2
are 0.25
. If we run the same code with outcome <- as.factor(c(rep("A",30),rep("B",30)))
instead, odds.ratio
will be 4
. This is because the opposite ratio is calculated, namely odds2/odds1
.
Further, as @Dason points out you can calculate one odds ratio
from the other one. See here
odds_ratio_a <- odds1/odds2
odds_ratio_b <- odds2/odds1
odds_ratio_a == 1/odds_ratio_b
# TRUE
odds_ratio_b == 1/odds_ratio_a
# TRUE
This is why in your case 1/ 1.127948 = 0.8865657
and 1/0.8865657 = 1.127948
.
The question remains why this happens. This is easy: Because the reference level changes! In as.factor(c(rep("C",30),rep("B",28)))
the reference level is "B" and in as.factor(c(rep("A",30),rep("B",28)))
it is "A". To get same results for both cases you need only to use outcome <-relevel(as.factor(c(rep("A",30),rep("B",28))), ref= "B")
.