Skip to content

Instantly share code, notes, and snippets.

@jrosell
jrosell / grammar-of-music.R
Created July 10, 2024 08:10
Head, shoulders, knees and toes...
# Ubuntu/debian: sudo apt-get install musescore
# pak::pak("flujoo/gm")
Sys.setenv(MUSESCORE_PATH = "/usr/bin/musescore")
library(gm)
(Music() +
Meter(4, 4) +
Line(
pitches = c(
c("G4", "A4", "G4", "F#4"),
---
title: "robo violencia"
output: html_document
date: "2024-06-19"
editor_options:
chunk_output_type: console
---
## CCAA
get_mode <- \(x) {
r <- table(x)
names(r[r == max(r)])
}
# For example:
# > get_mode(c(1,2,2,3,3,4))
# 2 3
#!/usr/bin/env Rscript
cat("==========================================================================\n")
cat("Example of strategy patern in R: Multiple ways to show routes. \n")
# Problem:
# You build a navigation app for casual travelers and help users quickly orient themselves in any city.
#
# - The first only build the routes over roads.
# - Next update, you added an option to build walking routes.
@jrosell
jrosell / shiny-javascript-communication.R
Last active April 5, 2024 12:44
Update value in a hidden field from R or from JavaScript using the Shiny package.
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
hidden(
textInput("my_input", label = "my_input", value = "Initial value")
),
textOutput("my_output"),
actionButton("my_js_button","Update from JavaScript"),
@jrosell
jrosell / pluja.R
Last active March 26, 2024 17:14
Adapating code from https://github.com/milos-agathon/precipitation-maps to compare spain precipitation in 2023 and previous years
## Preparations
pkgs <- c("tidyverse", "pRecipe", "giscoR", "terra", "rayshader", "patchwork")
rlang::check_installed(pkgs)
suppressPackageStartupMessages({
invisible(lapply(pkgs, library, character.only = TRUE, quietly = TRUE))
})
# Dades per CCAA ===============================================================
library(tidyverse)
library(rvest)
theme_set(theme_minimal())
older_year <- 2002
region <- tibble(
slug = c("andalucia", "aragon", "asturias", "canarias", "cantabria", "castilla-leon",
"castilla-la-mancha", "cataluna", "ceuta", "melilla", "madrid", "valencia",
library(tidyverse)
x <- list(a = list(b = 1, c = NULL), d = NULL)
get_list_names <- \(x, y = c()){
if (!is.null(names(x))){
for (nm in names(x)) {
y <- get_list_names(x[[nm]], c(y, nm))
}
}
@jrosell
jrosell / game-of-life-coro-generators.R
Created February 27, 2024 16:28
Game of Life using {coro} generators in R
# Game of Life using {coro} generators in R
# Inspiration from Jack Diederich's Python implementation: https://gist.github.com/jhrr/2b5a60e9efcb573c9cc4
library(tidyverse)
library(coro)
library(zeallot)
generate_neighbors <- generator(function(point) {
c(x, y) %<-% point
yield(c(x + 1, y))
# preallocates memory.
fmat <- function(n) {
res <- matrix(NA, n, n)
for (i in 1:n) {
res[i, ] <- runif(n)
}
res
}
# rbind each time