#' Extract Left-Hand Side Variable Names from a Stargazer Table
#'
#' This function extracts the names of the left-hand side (dependent) variables
#' from a `stargazer` generated LaTeX table. It assumes the default
#' `stargazer` table format where the dependent variable names are listed
#' below the "Dependent variable" line.
#'
#' @param star A character vector representing the lines of a LaTeX table
#' generated by `stargazer`. This is typically obtained by reading the
#' output of `stargazer` into R using `readLines()`.
#'
#' @return A character vector containing the names of the left-hand side
#' variables.
#'
#' @details This function relies on the specific formatting of default
#' `stargazer` tables. If you have customized the table's appearance
#' (e.g., by adding or removing rows, or changing the labels), this function
#' may not work correctly. It also assumes that the table is a regression
#' table and not another type of table. It will only work if the table
#' includes the line "Dependent variable".
#'
#' @examples
#' library(stargazer)
#'
#' data(mtcars)
#' mod.mtcars.1 <- lm(mpg ~ hp + wt, mtcars)
#' mod.mtcars.2 <- lm(mpg ~ hp + wt + cyl, mtcars)
#' mod.mtcars.3 <- lm(hp ~ wt + cyl, mtcars)
#'
#' star_get_lhs_names(stargazer(mod.mtcars.1))
#' star_get_lhs_names(stargazer(mod.mtcars.1, mod.mtcars.2))
#' star_get_lhs_names(stargazer(mod.mtcars.1, mod.mtcars.2, mod.mtcars.3))
#' @export
star_get_lhs_names <- function(star) {
if (!is.latex(star))
stop("Error: `star_get_lhs_names` only works on stargazer regression latex tables")
## Assume that the lhs vars are right below the "Dependent variable" line
dep.var.row <- grep("Dependent variable", star)
lhs.vars <- star[c(dep.var.row + 2)] %>%
gsub("\\\\\\\\", "", x = .) %>%
sub("\\[-1.8ex\\]", "", x = .) %>%
strsplit(x = ., "&") %>%
unlist(.) %>%
stringr::str_trim() %>%
.[2:length(.)]
if (length(lhs.vars) > (star_ncol(star) - 1))
stop("Error: In `star_get_lhs_names`, the length of the LHS variables greater than `star_ncol(star) - 1`. Are you sure you are passing a default stargazer latex regression table to `star_get_lhs_names`")
return(lhs.vars)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.