Manipulating labels and levels in tbl_regression (gtsummary) with multinom (nnet) - r

It seems the functions for manipulating labels and levels in tbl_regression tables do not work with multinom from the nnet library. Here is reproducable code with the resulting tables. Does anyone have a clue how to get my labels bold and italicized in multinom? Thanks!
library(nnet)
library(gtsummary)
library(tidyverse)
# Create a sample data frame
set.seed(123)
df <- data.frame(
y = sample(c(0, 1, 2), 100, replace = TRUE),
var1 = rnorm(100),
var2 = rnorm(100),
var3 = rnorm(100)
)
# Fit a multinomial logistic regression model with nnet
model <- multinom(y ~ var1 + var2 + var3, data = df)
# Create a summary table with tbl_regression
model_tab <- tbl_regression(model,
exponentiate = TRUE) %>%
bold_labels() %>%
italicize_labels()
model_tab
# Fit a linear regression model
model_2 <- glm(var1 ~ var2 + var3, data = df, family = "gaussian")
# Create a summary table with tbl_regression
model_2_tab <- tbl_regression(model_2) %>%
bold_labels() %>%
italicize_labels()
model_2_tab

If an html document is alright, as I suggested in the comments, you can do it with CSS. In particular, in an RMarkdown document, you would need to put a code chunk that looks like this:
```{css echo=FALSE}
td.gt_row.gt_left{
font-weight: bold;
font-style: italic;
}
```
Then the you could put your code chunk for the table:
```{r echo=FALSE, results="asis"}
tbl_regression(model, exponentiate = TRUE) %>%
bold_labels() %>%
italicize_labels()
```
and in the rendered html document, the labels would show up in bold and italics:
For the categorical variables, the text is indented, so you could differentially change the row headings that are indented. The second block of code in the chunk below sets the indented entries to normal font.
```{css echo=FALSE}
td.gt_row.gt_left{
font-weight: bold;
font-style: italic;
}
td.gt_row.gt_left[style*="text-indent: 10px"]{
font-weight: normal;
font-style: normal;
}
```
I made var1 categorical and here's the resulting table.

Related

Formatting regression results in R for latex

I am trying to create a regression results table in R for latex. I would like this table to have two separate columns: one for the estimates and one for the standard error. The following code
library(fixest)
library(car)
library(pander)
##Using the built-in CO2 data frame, run regression
i<- feols(conc ~ uptake + Treatment | Type, CO2, vcov = "hetero")
summary(i)
##Create regression table for latex
etable(i, postprocess.df = pandoc.table.return, style = "rmarkdown")
my_style = style.df(depvar.title = "", fixef.title = "",
fixef.suffix = " fixed effect", yesNo = "yes", default = TRUE)
setFixest_etable(style.df = my_style, postprocess.df = pandoc.table.return)
etable(i, style = "rmarkdown", caption = "New default values", se.below = NULL )
etable(i, tex = TRUE)
print(etable(i, tex = TRUE), file = "filename2.tex")
When put into Latex document on overleaf.com the following image is produced.
How can I alter my above code to have estimates and standard error in different columns in my table?
You can try the following:
modelsummary(your_regression, fmt=2,
estimate = c("{estimate}{stars} (std.error)"),
statistic = c(),
output = "latex")
What I like with modelsummary too, is that it enable to put many different model as a list to compare them.
Thanks to #léo-henry for suggesting modelsummary. I just wanted to point out that in the latest version of the package you can use the shape argument to display the estimates and standard errors (or other statitics) side-by-side. You will find details here: https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.html#shape
Here is a minimal example:
library(modelsummary)
mod <- lm(mpg ~ hp + drat, data = mtcars)
modelsummary(mod, shape = term ~ model + statistic)

Texreg: Format "groups"-headings with bold, italics etc

I am using the texreg-package to output nice regression tables in R.
However, when using the groups parameter to group variables, I would like to format the headings with bold/italics or similar to make them stand more out. One possible solution is to export the texreg using htmlreg and manually adding font-weight: bold; in the style parameters (and I guess that there are similar fixes for each output-type).
Do anyone know if there is an easier way that it can be done - before leaving R?
Here is an example from their own documentation with groups headings added:
library("nlme")
library("texreg")
model.1 <- lme(distance ~ age, data = Orthodont, random = ~ 1)
model.2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)
texreg(list(model.1, model.2), booktabs = TRUE, dcolumn = TRUE, groups = c("A" = list(1:1), "B" = list(2:3)))

Extract regression summary() output in word document in a nicely formated resut [duplicate]

This question already has an answer here:
Extract summary of regression model in latex
(1 answer)
Closed last year.
Is there a way to extract the summary of a regression model in a nice latex format like the correlation table I attach below? The table should be exported using knitr in word document or at least saved in word document.
# install.packages("dplyr")
# install.packages("kableExtra")
library(dplyr)
library(kableExtra)
mlm1 <- lm(mpg ~ . , data = mtcars)
summary(mlm1)
summary(mlm1) %>%
kbl(caption="Table 1: Summary Statistics of Financial Well-Being
Score by Gender and Education",
format= "html",
align="r") %>%
kable_classic(full_width = F, html_font = "helvetica")
you can use the broom package:
library(dplyr)
library(kableExtra)
library(broom)
mlm1 <- lm(mpg ~ . , data = mtcars)
summary(mlm1)
tidy(mlm1) %>% kbl(caption="Table 1: Summary Statistics of Financial Well-Being
Score by Gender and Education",
format= "html",
align="r") %>%
kable_classic(full_width = F, html_font = "helvetica")
Also, you can reports information about the entire model (i.e. R-squared, AIC, ...) via broom::glance(mlm1).

Removing table components in stargazer

I am putting together tables using stargazer and presenting them in a HTML file using RMarkdown. Reproducible code to create the image is pasted below.
I would like to remove the stars and standard errors associated with the constant ("Alpha" in the image below).
I understand that I can manually overwrite the table components but is there a way that I can automatically retain stars and SE for everything but the alpha row? To re-write everything into character vectors seems a little cumbersome.
Code:
library(tidyverse)
library(stargazer)
mdl1 <- lm(mpg~wt, mtcars)
mdl2 <- lm(mpg~disp, mtcars)
mdls <- list(mdl1,mdl2)
column.labels <- c('model 1',
'model 2')
covariate.labels <- c('Beta 1',
'Beta 2',
'Alpha')
keep.stat <- c('n')
stargazer(mdls, type = 'html',
column.labels = column.labels,
covariate.labels = covariate.labels,
column.sep.width = "10pt",
dep.var.labels.include = F,
keep.stat = keep.stat)
In a comment you asked if an alternative to stargazer could help you
with this. The answer is “yes”, the modelsummary
package can do this
relatively easily. (Disclaimer: I am the maintainer.)
I say “relatively” because what you are asking is very idiosyncratic, so
I don’t think you should expect it to work out of the box in any
package. But here’s an example.
First, we start with a basic table with nice labels:
library(modelsummary)
library(broom)
models <- list(
lm(mpg ~ wt + hp, mtcars),
lm(mpg ~ disp + hp, mtcars))
coef_map <- c(
"wt" = "Weight",
"disp" = "Displacement",
"hp" = "Horse Power")
modelsummary(models, stars = TRUE, coef_map = coef_map)
The Customizing Existing Models
section
of the documentation explains that modelsummary allows you to
overwrite any estimate (coef, standard error, p value, etc.) by defining
a new function called tidy_custom.CLASSNAME, where CLASSNAME refers
to the type of model object you are trying to summarize.
In our example above, we summarize lm models:
class(models[[1]])
## [1] "lm"
Therefore, our customizing function will be called tidy_custom.lm. Say
your goal is to remove the standard errors, stars, and p values from the
table, but only for the variable hp. What we can do is overwrite the
estimates with NA (please refer to the docs linked above for a
detailed explanation):
tidy_custom.lm <- function(model) {
out <- tidy(model)
out$p.value[out$term == "hp"] <- NA
out$std.error[out$term == "hp"] <- NA
return(out)
}
modelsummary(models, stars = TRUE, coef_map = coef_map)

Create a table of logistic regression results in R markdown

I would like to create a regression table in R Markdown that includes the exponentiated coefficients, exponentiated upper and lower 95% confidence intervals and p-value for each variable in a logistic regression model.
```{r}
#basic table
library(knitr)
x1 <- rnorm(100,0,1)
x2 <- rpois(100,5)
y1 <- rbinom(100,1,0.33)
df <- data.frame(x1,x2,y1)
modelx <- glm(y1 ~ x1 + x2, data = df ,family = "binomial")
kable(summary(modelx)$coef)
#maneuvers to obtain OR and 95% CI
orx <- exp(c(OR = coef(modelx), confint(modelx)))
kable(orx)
```
I've tried as above, which creates the values, but loses the labels and general kable-friendly form. I have tried directly replacing the exponentiated coefficients into the glm object modelx. However, this object cannot easily hold the 95% CI.
Is there a simple way to accomplish this task without manually building the table in tables or other kable-friendly package?
The process requires transforming the summary(modelx) to a data.frame, carry out the necessary calculations while adding results to the data.frame and finally porting to kable with kableExtra options to finish the formatting.
```{r results='asis', echo=FALSE}
#basic table
library(knitr)
library(kableExtra)
x1 <- rnorm(100,0,1)
x2 <- rpois(100,5)
y1 <- rbinom(100,1,0.33)
df <- data.frame(x1,x2,y1)
modelx <- glm(y1 ~ x1 + x2, data = df ,family = "binomial")
tableit <- data.frame(summary(modelx)$coef)
tableit$OR <- exp(tableit$Estimate)
tableit$LCL <- exp(tableit$Estimate - tableit$Std..Error * 1.96 )
tableit$UCL <- exp(tableit$Estimate + tableit$Std..Error * 1.96 )
tableit$`p-value` <- tableit$Pr...z..
tableit <- tableit[c(5,6,7,8)]
kable(tableit, digits = 2, align = rep('c',4 )) %>%
kable_styling(bootstrap_options = "striped", full_width = F)
```

Resources