Skip to content

Instantly share code, notes, and snippets.

@noamross
noamross / webr-xhr.R
Last active December 21, 2023 15:07
Experiments with WebR + XHR
# This function successfully runs the XHR request
# No response in the browser console because it is
# running in a web worker
webr::eval_js("
async function run() {
let response = await fetch('https://httpbin.org/json');
let data = await response.json();
return data;
}
run().then(data => console.log(data));
@noamross
noamross / afile.txt
Created December 1, 2023 23:55
This is a text file
This is a text file on the web
@noamross
noamross / afile.txt
Created December 1, 2023 23:55
This is a text file
This is a text file on the web"
@noamross
noamross / dput_binary.R
Last active November 17, 2023 03:22
dput() but with compressed binary serialized to 7-bit character text ¯\_(ツ)_/¯
dput_binary <- function(object, compression = "xz") {
encoded <- strsplit(rawToChar(serialize(memCompress(serialize(object, NULL), type = compression), NULL, ascii = TRUE)), "\n")[[1]]
header <- gsub(" ", "", capture.output(dput(encoded[c(1:8)])))
body <- paste0("\"", paste(encoded[-c(1:8)], collapse = ""), "\"")
#The `gsub()` call here is to remove any whitespace or newlines introduced in
#printing and copy/paste
all <- paste0(
'unserialize(memDecompress(unserialize(textConnection(c(gsub("[\\\\s\\\\n]","",',
@noamross
noamross / tar_load_version.R
Last active November 3, 2023 18:55
Read previous versions of targets from git repository
# Requires a development branch of git2r for now. Do `remotes::install_github('ropensci/git2r@raw-blob-content')` or
# `renv::install('ropensci/git2r@raw-blob-content')`. This installs from source.
# TODO:
# - Add a function to extract an arbitrary file/folder, e.g., copy_git_file(path, ref, repo)
# - Have tar_*_version check if the target is a local file and in that case extract it and return a temporary path (turn on/off with arguments)
# - Guardrails and informative error messages cases such as: Not a git repository, target not present at the given reference, remote version not available. What happens with shallow clones?
# - Maybe only extract stuff in the `objects/` directory when needed
library(git2r)
@noamross
noamross / ocat.R
Created May 31, 2023 00:18
Example code for an ordered categorical model
library(mgcv)
library(ggplot2)
library(dplyr)
## Simulate data with two categories and outcomes in 1:10
## Outcomes must be positive nonzero integers, transform if necessary
set.seed(3);
dat$Group = as.factor(paste("Group", rep(1:2, each = 200)))
dat$y = as.integer(round(pmax(pmin(rnorm(400, ifelse(dat$Group == "Group 1", 4, 6), 3), 10), 1)))
@noamross
noamross / sample_gam_posterior.R
Created May 1, 2023 14:25
Parallel chains with gam.mh()
sample_gam_posterior <- function(multinomial_model,
chains = 4,
cores = min(chains, parallel::detectCores()), ...) {
samps <-
purrr::transpose(parallel::mclapply(
X = seq_len(chains),
FUN = function(X) {
post <- gam.mh(multinomial_model, ...)
library(xgboost)
library(reticulate)
#reticulate::py_install("m2cgen") # https://github.com/BayesWitnesses/m2cgen
#reticulate::py_install("xgboost")
#reticulate::py_install("sklearn")
# Fit an XGBoost Model (example from ?xgb.train)
data(agaricus.train, package='xgboost')
data(agaricus.test, package='xgboost')
@noamross
noamross / test-missing-mrf.R
Last active January 21, 2023 20:18
Testing reduced-rank missing data strategies with mgcv
# Testing missing data strategies with mgcv
library(mgcv)
library(MRFtools) # github.com/noamross/MRFtools
library(tidyverse)
# Simulate data with missing parts
n <- 350;set.seed(2)
dat <- gamSim(1,n=n,scale=3) ## 1 or 7
drop <- sample(1:n,300) ## to
for (i in 2:5) dat[drop[1:75+(i-2)*75],i] <- NA
@noamross
noamross / _targets.R
Created December 13, 2022 12:48
A {targets} workflow to nuke all your twitter data
# A Targets workflow to nuke your Twitter data
# Still working around some rate limits,
# I suggest building each of the deletion targets
# individually, e.g., "tar_make(blockunblock)"
# Load packages required to define the pipeline:
library(targets)
library(tarchetypes)
library(tidyverse)
library(rtweet)
library(jsonlite)