Skip to content

Instantly share code, notes, and snippets.

View andrewheiss's full-sized avatar
👨‍💻
#rstats-ing all the things

Andrew Heiss andrewheiss

👨‍💻
#rstats-ing all the things
View GitHub Profile
library(tidyverse)
library(wakefield)
library(rdrobust)
library(rddensity)
library(broom)
library(huxtable)

# Make fake data
set.seed(1234)
---
title: "Testing with lots of plots"
---
```{r}
#| label: fun-generate-chunks
#| include: false
generate_chunk <- function(id) {
paste0(
---
title: "Testing"
---
```{r}
#| label: fun-generate-chunks
#| include: false
generate_chunk <- function(id) {
paste0(
library(tidyverse)
library(marginaleffects)
library(gapminder)

gapminder_2007 <- gapminder |> 
  filter(year == 2007)

# Use log() in the model formula
model <- lm(lifeExp ~ log(gdpPercap), data = gapminder_2007)
@andrewheiss
andrewheiss / html2docx.scpt
Created February 4, 2016 21:09
Convert HTML file to docx with Applescript (*and* embed linked images!)
set base_folder to "FOLDER/NAME/HERE/"
set file_in to base_folder & "FILENAME.html"
set file_out to base_folder & "FILENAME.docx"
tell application "Microsoft Word"
activate
open file_in
set all_images to inline pictures of active document
repeat with img in all_images
library(tidyverse)
library(mlogit)
library(dfidx)
library(marginaleffects)

chocolate <- read_csv("https://www.andrewheiss.com/blog/2023/08/12/conjoint-multilevel-multinomial-guide/data/choco_candy.csv") %>% 
  mutate(
    dark = case_match(dark, 0 ~ "Milk", 1 ~ "Dark"),
    dark = factor(dark, levels = c("Milk", "Dark")),
library(tidyverse)
library(palmerpenguins)

penguins <- penguins |> drop_na()

# This splits the dataset into three smaller datasets behind the scenes, but
# then doesn't do anything with them. But secretly it's waiting to do things
# within the three groups (hence the "Groups: species [3]") note
penguins |> 
library(tidyverse)
library(tinytable)
inline_listify <- function(x) {
numbers <- seq_along(x)
prefixed <- paste0("(", numbers, ") ", x)
collapsed <- paste(prefixed, collapse = "; ")
return(collapsed)
}
library(tidyverse)
library(broom)

model1 <- lm(hwy ~ displ + cyl, data = mpg)
model2 <- lm(hwy ~ displ + cyl + drv, data = mpg)

plot_data <- bind_rows(
  tidy(model1, conf.int = TRUE) |> mutate(model = "Model 1"),
 tidy(model2, conf.int = TRUE) |&gt; mutate(model = "Model 2")
library(tidyverse)
library(gapminder)
# ifelse() will happily work and coerce your numbers into text
gapminder1 <- gapminder |>
mutate(life_cat = ifelse(lifeExp > 75, "High", lifeExp))
# if_else() will yell at you
gapminder1 <- gapminder |>
mutate(life_cat = if_else(lifeExp > 75, "High", lifeExp))