Created
May 6, 2024 16:15
-
-
Save yjunechoe/a0739defa4057f5c2a6af28095b25416 to your computer and use it in GitHub Desktop.
Convert lme4 double-bar syntax to MixedModels.jl zerocorr()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(rrapply) | |
expr <- y ~ x + (1 || z) | |
lobstr::ast(!!expr) | |
#> █─`~` | |
#> ├─y | |
#> └─█─`+` | |
#> ├─x | |
#> └─█─`(` | |
#> └─█─`||` | |
#> ├─1 | |
#> └─z | |
# `{rrapply}`-style functions to locate replacement points in the AST | |
is_parens_doublebar <- function(x, .xsiblings) { | |
identical(x, quote(`(`)) && | |
identical(.xsiblings[[2]][[1]], quote(`||`)) | |
} | |
is_doublebar_zerocorr <- function(x, .xparents) { | |
identical(x, quote(`||`)) && { | |
object <- evalq(object, parent.frame()) | |
doublebar_parent <- as.integer(head(.xparents, -2)) | |
identical(object[[doublebar_parent]][[1]], quote(zerocorr)) | |
} | |
} | |
# Helper to return symbols to replace with | |
returnq <- function(x) { | |
eval(substitute(function(...) quote(x))) | |
} | |
convert_to_zerocorr <- function(x) { | |
x <- rrapply(x, is_parens_doublebar, f = returnq(zerocorr), how = "replace") | |
x <- rrapply(x, is_doublebar_zerocorr, f = returnq(`|`), how = "replace") | |
x | |
} | |
convert_to_zerocorr(expr) | |
#> y ~ x + zerocorr(1 | z) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Even more over-engineered version that collapses
rrapply()
calls: