RSSAmplifier

Blog

coolbutuseless

Recent content on coolbutuseless

coolbutuseless.github.ioRSS feed ↗254 posts

Latest posts

Toy WASM interpreter in base R

WASM One of the big buzzes at #RStudioConf2022 was the whiff of serverless “Shiny” in both python and R by harnessing WASM . WASM (a.k.a. WebAssembly) is a portable binary-code format initially targetted at running code in a web browser at near-native speeds. This post is a small exploration into what a WASM binary actually looks like and how it is structured. I also create a toy interpreter for…

AnotherWorld game written + playable in R (with {nara} and {eventloop})

AnotherWorld playable game in R This is the full code for a playable R version of the 16-bit game AnotherWorld The game plays in realtime using 2 key packages: {nara} for manipulation of nativeRaster images as a fast in-memory drawing canvas {eventloop} for event-driven interaction - allowing for keyboard feedback while rendering the game with sound. You can play this game today in R!! However,…

Pacman game written in R with {nara} and {eventloop}

Pacman-style game in R This is the full code for a playable, pacman-style game in R. The game plays in realtime using 2 key packages: {nara} for manipulation of nativeRaster images as a fast in-memory drawing canvas {eventloop} for event-driven interaction - allowing for keyboard feedback while rendering the game with sound. Gameplay Controls The aim of this pacman-style game is to eat all 288…

Introducing {nara} for nativeRaster handling for fast in-memory rendering buffers

nara {nara} provides tools for working with R’s nativeRaster image format to enable fast double-buffered graphics rendering. Why? nativeRaster buffers are fast enough to use for rendering at speed >30 frames-per-second. This makes them useful for games and other interactive applications. Example An example graphics demo is this non-playable version of pacman created and running in R in realtime…

World's simplest R music system. Part 3 - Non-sinusoidal Waveforms

Introduction A note doesn’t have to be a sine wave . Square, Triangle and sawtooth waves are also common and have different sound characteristics. Utilities developed in prior posts Click to reveal ADSR profiling and other utilities #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #' Create an ADSR profile of the given length - using only linear segments #' #' @param…

World's simplest R music system. Part 2 - linear ADSR note shaping

Introduction Using a raw sine curve as a note will lead to clipping artefacts as the note immediately starts with maximum amplitude and terminates abruptly. To make the note sound anything like an actual note from an instrument the profile of the note must be shaped to emulate the actual characteristics of a note produced by an actual physical object e.g. the note will ramp up to its playing…

World's simplest R music system

World’s simplest R mustic system #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Octaves/Notes/Frequencies in an equal tempered scale #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ets <- tibble( freq = 440 * (2 ^ ((-57:50)/12)), note = rep(c('C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'), 9), octave = rep(0:8, each…

{isocubes} v0.1.2 update with Signed Distance Fields

isocubes The purpose of this package is to provide a 3D rendering backend for a very particular visual aesthetic. That is, {isocubes} is an isometric rendering canvas with cubes as the only graphics primitive. Some tools are included for creating particular scenes, but in general, if you can provide a list of (x,y,z) integer coorindates of what to render, then isocumes will create a 3d render.…

Introducing isocubes - an isometric rendering backend

isocubes {isocubes} is an isometric rendering canvas with cubes as the only graphics primitive. What’s in the box isocubesGrob() to convert 3d integer coordinates into a grob for plotting coord_heightmap() to create coordinates for a heightmap from a matrix and (optional) colour information coord_sphere() to create coordinates for all isocubes within a sphere Coordinate system The size and…

Nesting Functions

Introduction Many structured formats for documents and data have a natural nested hierarchy. That is, there are lower-level elements nested within higher level structures A great xample of a nested document creation using nested function calls is HTML creation with {htmltools} . In the code below, the call to create the body() is nested within the function call to create the top-level html()…

Introducing `{tickle}` quickly build UIs in base R

tickle {tickle} is a package for creating UIs in base R. This is an opinionated abstraction over the base R package {tcltk} . This package aims to provide: a simplified UI creation process similar to shiny . a modern-looking visual default. more documentation to help create common UI elements without resorting to the online tcl/tk documentation. a way to still access the low-level tcl/tk…

Introducing `{tr808r}` a TR-808 Drum Machine in R

A TR-808 Drum machine in R using {eventloop} . Check it out on github ! Playback Your browser does not support the video tag. Realtime Interactive Pattern Editing Your browser does not support the video tag. Fetching patterns from tweets Your browser does not support the video tag.

A naive implementation of Visvalingam&#39;s line simplification in R

Visvalingham’s Line Simplification Algorithm Given a number of points defining a line Find the areas of the triangles defined by each set of 3 continuous points Remove the point which is the centre of the triangle with the minimum area Recalculate areas (as two will have changed when removing the point) Naive R implementation Full set of all triangle areas is calculated prior to the remove of each…

Introducing {eventloop} - Realtime interactive rendering in R

eventloop The {eventloop} package provides a framework for rendering interactive graphics and handling mouse+keyboard events from the user at speeds fast enough to be considered interesting for games and other realtime applications. {eventloop} is a wrapper around the built-in event handling available in base R as part of {grDevices} , but presents it in a more palatable format with some enhanced…

Introducing {cstructr} - a demonstration package showing how C structs may be exposed to R

cstructr {cstructr} is a demonstration package illustrating how a C struct may be wrapped and manipulated from within R as an external pointer. This is a “full-service” implementation which makes the internal values of the struct accessible from R via getters and setters. For bespoke solutions, a lot of the code could be excised to just keep some core functions. Note: The code in this package was…

Find sets of five words in the wordle dictionary that contain 25 unique letters

Find five words in the wordle dictionary that contain 25 unique letters While thinking about wordle I wondered if there existed any sets of five words in the wordle dictionary that would cover 25 unique letters of the alphabet. Given there are twelve thousand words in the wordle dictionary, there are 12000^5 five-word sets. This is approx 2.5x10^20 - which means that if I could test a million…

{wordle} v0.1.5 - a package for playing (and helping solve) Wordle puzzles

wordle The {wordle} package contains code to assist in finding good candidate words for Wordle. “Wordle” itself is a guess-a-word puzzle playable online . The game plays like the old ‘mastermind’ board game, but with letters instead of coloured pins. The gameplay is as follows: Enter a word as a guess for the hidden target word. Any letters which are within the hidden target word are coloured in…

Introducing {wordle} - a package for helping solve Wordle puzzles

wordle The {wordle} package contains code to assist in finding good candidate words for Wordle. “Wordle” itself is a guess-a-word puzzle playable online . The game plays like the old ‘mastermind’ board game, but with letters instead of coloured pins. The gameplay is as follows: Enter a word as a guess for the hidden target word. Any letters which are within the hidden target word are coloured in…

Solving a Wordle with assistance from R

Wordles! Wordles are a word guessing puzzle playable online . There’s a small write-up in a recent article in The Guardian The game plays like the old ‘mastermind’ board game, but with letters instead of coloured pins. Enter a word as a guess Any letters which are within the hidden target word are coloured in yellow. Any letters which match exactly the letter in the hidden target word are coloured…

Introducing {ggsvg} - use SVG as ggplot points

ggsvg - Use SVG as points in ggplot ggsvg is an extension to ggplot to use arbitrary SVG as points. This SVG can be customised to respond to aesthetics e.g. element colours can changes in response to fill and/or colour scales. However, aesthetics are not limited to colour - any other SVG parameter can be linked to any aesthetic which makes sense e.g. an aesthethic may be used to control the corner…

Lex, Parse and Evaluate a Simple S-Expression with {flexo}

library(flexo) {flexo} flexo is a package containing a simple lexer (to split text into named tokens) and a TokenStream R6 class for manipulating the stream (in order to iterate through the stream to parse it). LISPy S-Expression The following code is an S-Expression which evaluates to 21 sexp <- "(+ (* 2 3) (* 3 5))" Lex the S-Expression into tokens…

Base64 encoding/decoding in plain R

Introduction As part of working on {svgparser} I am adding support for the <image> tag in SVGs. <image> tags can reference an image as a URL, or they can also contain an inline copy of the image encoded in an “ASCII-safe” format. Base64 encoding is one commonly supported method for converting raw bytes into ASCII character strings. The following code is a mini-exploration into how Base64…

Introducing {svgparser} - an SVG renderer in plain R

svgparser Load SVG files as R vector objects (grobs) or data.frames svgparser loads vector-based SVG images as R vector objects. The vector objects which are created in R are the standard graphics object (‘grob’) in the base R {grid} graphics system. SVG images can also be imported as data.frames. Each shape, line and point is represented in the data.frame with copious helpings of metadata to…

A simple 2048 game engine in R

2048 in R A simple/naive implementation of 2048 in plain R - with {ggplot2} output for a little bit of zing. Interactive keypress response seems basically impossible from R, so this uses readline() and you have to press return to register each action. Code in a gist Motivation: Looking at some game stuff in R and this was the simplest thing I could think to write There’s an existing package on…

Custom {ggplot2} point shapes with {gggrid}

library(ggplot2) library(grid) library(gggrid) Use grobs as points in {ggplot} using {gggrid} I highly recommend reading Paul Murrel’s Report on {gggrid} and other techniques for getting grobs into ggplots . # remotes::install_github('https://github.com/pmur002/gggrid') library(grid) library(gggrid) hex <- FALSE if (hex) {…

Introducing {cssparser} - parse CSS into R lists and apply CSS to html within R

cssparser cssparser is a CSS parser (written in vanilla R) which can: Parse CSS into R lists Combine CSS Apply CSS to determine final computed styles of elements in an HTML document What’s in the box read_css() read a cascading style sheet consisting of multiple selectors into an R list read_inline_style() read a single inline style string into an R list css_apply() determine the calculated style…

Introducing {gozer} add destruction artefacts to R objects

gozer - choose the form of the destructor gozer allows you to attach a ‘destructor’ artefact (either a string or a function) to an R object. When the R object is destroyed (i.e. garbage collected) the ‘destructor’ artefact is printed or called. What’s in the box gozer() to attach a destructor artefact to an object. Installation You can install from GitHub with: # install.package('remotes')…

New {flexo} vignette - parsing subtitles in srt format

library(flexo) flexo : Simple Lex/Parse Tools in R {flexo} is a small package containing a lexer (for splitting text into tokens). The v0.2.6 update of flexo added support for stringi regex options like multiline support, and this vignette is a quick test of this new functionality. Parsing subtitles in srt format with flexo The srt subtitle format is a simple representation of subtitles for video…

Introducing {priorityqueue} - two simple priority queues. One written in R, the other in C

priorityqueue priorityqueue is a package with two priority queue implementations for R: one written in C, and the other written in plain R. Both of these are max-priority-queues i.e. “popping” from the queue returns the value with highest priority. These priority queues support any R object. The priority can be any finite double() value. What’s in the box Two priority queue implementations with…

Introducing {typhoid} uint16, fixedpt & numberwang implemented in vctrs

typhoid - non-standard numeric datatypes typhoid provides implementations of some non-standard datatypes using {vctrs} What’s in the box numberwang(x) for creating numeric values which present themselves as words. uint16(x) for creating 16-bit unsigned integers, where each value is stored as a pair of raw bytes. fixedpt(x, decimals = 3) for creating 32-bit fixed point numeric values. Each of the…

{smallfactor} update - store factors in bytes and bits rather than integers

smallfactor - store factors in bytes and bits rather than an integer smallfactor is an experiment to see what trade-offs there might be for storing a factor in bytes or bits instead of an integer. An R integer is 4-bytes, meaning it could hold a factor with two billion levels, which seems like overkill. bytefactor targets factors with up to 256 levels. bitfactor will choose the fewest bits to…

Introducing {numberwang} - numbers to words and vice versa)

numberwang numberwang will convert floating point numbers (and integers) to their word representations, and vice versa. The key differentiator of this package, compared to {nombre} , is that it supports decimal representations by listing individual decimal digits. See below for a comparison with {nombre} , {english} , {spanish} and {xfun} . What’s in the box num_to_words(num, decimals = 3)…

Introducing {smallfactor} - a space-saving factor backed by a raw vector (instead of integers)

smallfactor - store factors in raw rather than integer smallfactor is an experiment to see what tradeoffs there might be for storing a factor in a raw byte instead of an integer. Since an R raw value is only a single byte, but an integer is 4 bytes, there are space saving for large factors if stored in raw vector - as long as the number of levels is less than 256. What’s in the box smallfactor() -…

Fast(?) cubic beziers at variable resolution

I wanted to calculate some points along cubic bezier curves Current R grid bezier implementation is not a real bezier! According to docs for grid::bezierGrob() : “The curve is currently drawn using an approximation based on X-splines.” Code below is the fastest thing I could come up with (I’m only 80% sure it’s correct) It vectorized implemntation of the explicit form of the curve as explained on…

Introducing {colourmebad} - find pronounceable colours close to reference colours

colourmebad colourmebad provides some tools for finding pronounceable approximations to hex colours. These tools will be handy if you ever have to memorise a set of hex colours, or would like to impress people with your recall of a good colour palette as a party trick. In summary - no one needs these tools. This package was inspired by mdsumner ’s hexwords package. What’s in the box…

Introducing {ggqr} - A geom for QR codes in ggplot2

ggqr ggqr provides geom_qr() for inserting QR Codes into a plot. The core QR functionality is provided by Bob Rudis’s qrencoder package. What’s in the box geom_qr() to add QR codes to a plot grGrob() to create a QR grob Future Possibilities? Add automatic label positioning to avoid overlap of codes Installation You can install from GitHub with: # install.package('remotes')…

Introducing {bdftools} - tools for bitmap fonts in R

bdftools bdftools provides some tools for reading, manipulating and outputting BDF bitmap fonts. ToDo Todo: print header info when printing font Number of characters, width, height, bbox etc What’s in the box read_bdf(filename) reads a BDF pixel font file into an R representation i.e. an object of class bdf print.bdf() prints meta information and a font sample. bdf_create_df(bdf, text) Create a…

Introducing {facetious} - alternate facets for ggplot2

facetious facetious is home to some alternate facetting options for ggplot2 . What’s in the box facet_wrap_strict() respects nrow, ncol and inserts empty grobs to keep the resultant plot at the given size Otherwise works like ggplot2::facet_wrap() facet_grid_blank() When a factor level doesn’t exist, this facetting approach will insert a totally empty object, instead of just an empty plot…

Introducing {ingrid} - alternate tools for grab creation, manipulation and output

ingrid ingrid provides some tools that I find useful for creating/manipulating grid / grob objects interactively in the console. The name ingrid stands for IN teractive GRID The key benefits I get from ingrid : verbose output of grobs, gTrees and polyclipgrobs, with much more output than their default print methods from {grid} a suite of grob creation functions with inline gpar parameter…

Introducing &#39;sars&#39; - proof-of-concept for running &#39;SAS&#39; DATA and PROC SQL statements in R

sars sars is an totally useless, very experimental, proof-of-concept, oh-my-god-why package for executing sas DATA and PROC SQL statements in R. What’s in the box sars::run(code) to run some code as long as it is only DATA and PROC SQL statements and even then, not much of either of those statements is really supported either. Installation You can install from GitHub with: #…

R v4.1.0 - {grid} graphics new feature - patterns (part 3)

Introduciton As of R 4.1.0 there is built-in support for patterns in grid graphics. There are 3 types of pattern: grid::linearGradient() for linear colour gradients grid::radialGradient() for radial colour gradients grid::pattern() repetition of any combination of graphic objects (grobs) This quick post summarises a few more things which can be done with patterns: A mask with an alpha channel can…

R v4.1.0 - {grid} graphics new feature - patterns (part 2)

Introduciton As of R 4.1.0 there is built-in support for patterns in grid graphics. There are 3 types of pattern: grid::linearGradient() for linear colour gradients grid::radialGradient() for radial colour gradients grid::pattern() repetition of any combination of graphic objects (grobs) This quick post summarises a few things which can be done with patterns: creating a pattern a repeating element…

R v4.1.0 - {grid} graphics new feature - patterns

Introduciton As of R 4.1.0 there is built-in support for patterns in grid graphics. There are 3 types of pattern: grid::linearGradient() for linear colour gradients grid::radialGradient() for radial colour gradients grid::pattern() repetition of any combination of graphic objects (grobs) This quick post summarises a few things which can be done with patterns: creating a pattern a repeating element…

Introducing {gluestick} - a simple, base R, single function, glue-like string interpolator

gluestick The goal of the gluestick package is to provide a home for a single, simple function (also named gluestick ). This gluestick() function is meant to be an almost drop-in replacement for 99.9% of the reasons I use the amazing glue package. The idea is that you would just steal the function out of this package and use it in your own package in order to avoid having glue as a dependency.…

Package Development Update

Package Development Update plot(x=c(1.8, 4.2), y=c(0, 1), type = 'n', xlab = 'Time', ylab = 'Ideas', axes = F) N <- 1000 x <- numeric(N) x[1] <- 0.5 for (r in seq(2.4, 4, length.out = 3000)) { for (i in seq(N-1)) { x[i+1] <- r * x[i] * (1 - x[i]) } y <- unique(x[900:1000]) points(rep(r, length(y)), y, pch = '.', col = '#00000030') } title("Current Package Project in #RStats") text(1.8, 0.58, pos =…

Introducing &#39;fugly&#39; - fast regular expression substring extraction with named capture groups

fugly This package provides a single function ( str_capture ) for using named capture groups to extract values from strings. This function is just a wrapper around stringr . fugly::str_capture() is very similar to both unglue and utils::strcapture() . This package was written because stringr doesn’t yet do named capture groups (See issues for stringr and stringi ), and I needed something faster…

On &#39;on.exit()&#39; - Part 2

Introduction on.exit() is a base R function which records expressions to evaluate when the current function exits. I was wanting to use on.exit() in a function that was allocating some resources, and I explicitly wanted these resources freed in the reverse order. Working out how to do what I wanted was easy (discussed below), but it lead me down a path of discovery as I tried to figure out just…

On &#39;on.exit()&#39;

Introduction on.exit() is a base R function which records expressions to evaluate when the current function exits. I was wanting to use on.exit() in a function that was allocating some resources, and I explicitly wanted these resources freed in the reverse order. Working out how to do what I wanted was easy (discussed below), but it lead me down a path of discovery as I tried to figure out just…

Modifying R6 objects after creation - Part 2

R6 classes The {R6} package is an implementation of encapsulated object-oriented programming for R, and is a simpler, faster, lighter-weight alternative to R’s built-in reference classes. This style of programming is also sometimes referred to as classical object-oriented programming. In this post I’ll be using the word class to refer to the original class definition using R6::R6Class() and object…

Modifying R6 objects after creation

R6 classes The {R6} package is an implementation of encapsulated object-oriented programming for R, and is a simpler, faster, lighter-weight alternative to R’s built-in reference classes. This style of programming is also sometimes referred to as classical object-oriented programming. In this post I’ll be using the word class to refer to the original class definition using R6::R6Class() and object…