Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@
## 2024-05-15 - [R Performance: ifelse Overhead]
**Learning:** In R, ifelse evaluates both true and false branches entirely before subsetting, which is very inefficient for vector operations.
**Action:** Optimize this by preallocating with res <- Y * 0 to preserve attributes and using vectorized subsetting like if any cond res subset <- ...

## 2024-05-16 - Safe ifelse Optimization with Mathematical Operations in R
**Learning:** While replacing `ifelse(n == 0, 0, y/n)` with pre-allocation (`y_res <- y * 0; y_res[cond] <- ...`) works, it can be mathematically simplified to `y_res <- y / n; y_res[n == 0 & !is.na(n)] <- 0`. The key learning is that subsetting *must* explicitly check `!is.na(n)` to avoid throwing a fatal "NAs are not allowed in subscripted assignments" error if `n` contains missing values, making the code safer and more readable.
**Action:** When replacing `ifelse` via mathematical shortcuts, always combine the logical condition with `& !is.na(...)` to preserve NA handling robustly.
8 changes: 6 additions & 2 deletions R/llcont.R
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,16 @@ llcont.glm <- function(x, ...){
if(is.matrix(y)) {
## Bolt: replaced apply(..., 1, sum) with optimized rowSums() for performance
n <- rowSums(y)
y <- ifelse(n == 0, 0, y[, 1]/n)
## Bolt: optimized ifelse for performance
y <- y[, 1] / n
y[n == 0 & !is.na(n)] <- 0
} else {
n <- rep.int(1, length(y))
}
m <- if (any(n > 1)) n else wt
wt <- ifelse(m > 0, (wt/m), 0)
## Bolt: optimized ifelse for performance
wt <- wt / m
wt[m <= 0 & !is.na(m)] <- 0
dbinom(round(m * y), round(m), mpreds, log = TRUE) * wt
},
quasibinomial = {
Expand Down
Loading