benjaminrich / table1

79 stars 26 forks source link

p value for multiple logistic regression model #87

Closed tianfeiwei closed 2 years ago

tianfeiwei commented 2 years ago

Hi Benjamin, thanks a lot for making such a great package. It's extremely handy. I was trying to make my own tweaks of p-value function for logistic regression model, but the final p-value seems not match with my manually calculated p-values. Could you please guide me on this?

pvaluetemp <- function(x, ...) {
    x <- x[-length(x)]  # Remove "overall" group
    y <- unlist(x)
    g <- factor(rep(1:length(x), times=sapply(x, length)))
    # p <- kruskal.test(y ~ g)$p.value
    p <- summary(glm(g ~ y+disp + hp + drat,data=mtcars,family = binomial(link = "logit")))$coef[2,4]
    c("", sub("<", "<", format.pval(p, digits=3, eps=0.001)))
}

mtcars$wtf <- ifelse(mtcars$wt > 3, 1, 0)
table1(~ mpg | wtf, data = mtcars, extra.col=list(`P-value`=pvaluetemp), extra.col.pos = c(3))

image

but summary(glm(wtf ~ mpg+disp + hp + drat,data=mtcars,family = binomial(link = "logit")))$coef[2,4] gives me 0.7562281.

Not sure what did I do wrong? Or is there any alternative ways to just manually input values as extra.custom.col=list(P-value=c(0.756))? Thanks

benjaminrich commented 2 years ago

I see the problem, but I don't quite understand the example (seems a little strange to me). You can get the result you want by sorting the mtcars data first, like this:

mtcars$wtf <- ifelse(mtcars$wt > 3, 1, 0)
mtcars <- mtcars[order(mtcars$wtf),]

table1(~ mpg | wtf, data = mtcars, extra.col=list(`P-value`=pvaluetemp), extra.col.pos = c(3))

image

EDIT: If you really prefer to input the value manually, you can do it using an anonymous function, like this:

table1(~ mpg | wtf, data = mtcars, extra.col=list(`P-value`=\(...) "0.756"), extra.col.pos = c(3))
tianfeiwei commented 2 years ago

Thank you, this helps a lot!