title: “kdm_data 9.22.25 after lunch” output: html_document date: “2025-09-22” —

This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code.

Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter.

Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.

R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(brglm2)    # Firth/bias-reduced logistic
library(broom)
library(dplyr)
df <- read.csv("kdm_data.csv") 
# Ensure factors with desired baselines
df <- df %>%
  mutate(
    RNAi = relevel(factor(RNAi),ref = "LexA"),
    Genotype = relevel(factor(Genotype), ref = "HWT")
  )
mods <- setdiff(levels(df$RNAi), "LexA")
one_mod_test <- function(mod_name) {
  sub <- df |> filter(RNAi %in% c("LexA", mod_name)) |> droplevels()
  # Make sure LexA is baseline and HWT is baseline
  sub$RNAi     <- relevel(sub$RNAi, "LexA")
  sub$Genotype <- relevel(sub$Genotype, "HWT")
  # Full model has the interaction = DID we care about
  m_full <- glm(cbind(Males, Females) ~ Genotype * RNAi,
                family = binomial(), data = sub, method = brglm2::brglmFit)
  # Reduced model = no interaction (no extra K16R drop under this modifier)
  m_red  <- update(m_full, . ~ . - Genotype:RNAi)
  # Likelihood-ratio test for that one interaction
  lrt <- anova(m_red, m_full, test = "LRT")
  p_lrt_two <- lrt$`Pr(>Chi)`[2]
  # Pull the interaction coefficient (effect size)
  rn <- grep("^GenotypeK16R:RNAi", rownames(coef(summary(m_full))), value = TRUE)
  co <- coef(summary(m_full))[rn, , drop = FALSE]
  beta <- co[1, "Estimate"]         # log ratio-of-odds-ratios (log ROR = DID)
  se   <- co[1, "Std. Error"]
  ROR  <- exp(beta)
  # One-sided p (directional: expecting beta < 0)
  p_one <- if (beta < 0) p_lrt_two/2 else 1 - p_lrt_two/2
  tibble(
    RNAi = mod_name,
    log_ROR = beta, SE = se, ROR = ROR,
    p_LRT_two_sided = p_lrt_two,
    p_LRT_one_sided_DIR_is_ROR_lt_1 = p_one
  )
}
res <- bind_rows(lapply(mods, one_mod_test)) |>
  mutate(p_FDR_one_sided = p.adjust(p_LRT_one_sided_DIR_is_ROR_lt_1, method = "BH")) |>
  arrange(p_FDR_one_sided)
library(dplyr)
library(emmeans)
## Welcome to emmeans.
## Caution: You lose important information if you filter this package's results.
## See '? untidy'
library(brglm2)
# --- Load data (edit path if needed) ---
df <- read.csv("kdm_data.csv", stringsAsFactors = FALSE)
# --- Ensure factors & baselines (HWT, LexA) ---
df <- df %>%
  mutate(
    RNAi     = relevel(factor(RNAi),     ref = "LexA"),
    Genotype = relevel(factor(Genotype), ref = "HWT")
  )
# --- Firth (bias-reduced) logistic on the full dataset ---
model <- glm(
  cbind(Males, Females) ~ Genotype * RNAi,
  family = binomial(),
  data   = df,
  method = brglm2::brglmFit
)
# --- EMMs on logit scale, simple effect (K16R - HWT) within each RNAi ---
emm  <- emmeans(model, ~ Genotype | RNAi)          # stays on link (logit) scale
simp <- contrast(emm, "revpairwise")               # K16R - HWT because HWT is the ref
# --- DID vs LexA: (simple_effect at modifier) - (simple_effect at LexA) ---
levs <- levels(simp)$RNAi
stopifnot("LexA" %in% levs)
did <- contrast(
  simp,
  method = "trt.vs.ctrl",
  ref    = which(levs == "LexA"),
  by     = "contrast"
)
# --- Summarize (no multiple-testing adjustment here; we do our own) ---
s <- summary(did, infer = TRUE, adjust = "none")
# Parse modifier name from “X - LexA” and clean any parentheses
mod_name <- gsub("[()]", "", sub(" - LexA$", "", s$contrast))
# One-sided p for the direction you expect (K16R < HWT => log_ROR < 0)
z <- s$estimate / s$SE
p_one <- pnorm(z, lower.tail = TRUE)  # one-sided "less"
# BH–FDR across modifiers
p_fdr <- p.adjust(p_one, method = "BH")
# Add interpretable effect sizes (ratio of odds ratios) and 95% CI
res <- data.frame(
  RNAi        = mod_name,
  log_ROR     = s$estimate,
  SE          = s$SE,
  z           = z,
  p_one_sided = p_one,
  p_FDR_one_sided = p_fdr,
  ROR         = exp(s$estimate),
  ROR_LCL95   = exp(s$estimate - 1.96 * s$SE),
  ROR_UCL95   = exp(s$estimate + 1.96 * s$SE)
) %>%
  arrange(p_FDR_one_sided)
res

```