Skip to content

Instantly share code, notes, and snippets.

View alekrutkowski's full-sized avatar

alek alekrutkowski

View GitHub Profile
@alekrutkowski
alekrutkowski / lib.rs
Last active November 20, 2024 15:59
Rust extendr/rextendr code to take R's data.frame and a file path as inputs, and save the data.frame in an Excel file
// Conversion of missing values doesn't work!!! -- to be corrected
use extendr_api::prelude::*;
use umya_spreadsheet::*;
use umya_spreadsheet::writer::xlsx;
#[extendr]
fn save_dataframe_to_excel(df: Robj, file_path: &str) -> extendr_api::Result<()> {
// Ensure the input is a DataFrame
let dataframe = df
@alekrutkowski
alekrutkowski / lib.rs
Last active November 19, 2024 09:23
Rust extendr/rextendr code to take R's data.frame as input, modify it as a polars DataFrame (add columns), and return a modified R data.frame.
use extendr_api::prelude::*;
use polars::prelude::*;
// Helper function to convert an R data.frame to a Polars DataFrame
fn r_to_polars_dataframe(r_df: List) -> Result<DataFrame> {
let mut columns = Vec::new();
for (name, col) in r_df.iter() {
let col_name: PlSmallStr = name.into(); // Convert column name to PlSmallStr
@alekrutkowski
alekrutkowski / lib.rs
Last active November 11, 2024 11:28
Rust extendr/rextendr code to take R's data.frame as input, modify it (add columns), and return a modified data.frame
use extendr_api::prelude::*;
use rand::{distributions::Alphanumeric, Rng};
use std::collections::HashMap;
// Define the function to be used in R
#[extendr]
fn add_columns(df: Dataframe<Robj>) -> List {
// Get the number of rows in the data frame
let n_rows = df.get_attrib("row.names").unwrap().len();
@alekrutkowski
alekrutkowski / lib.rs
Last active November 5, 2024 08:17
Rust extendr/rextendr code to transpose R's character matrix
use extendr_api::prelude::*;
#[extendr]
fn transpose_char_matrix(matrix: RMatrix<Rstr>) -> Robj {
// Take the input dimensions
let dims = matrix.dim();
// Get the number of rows and columns
let nrows = dims[0] as usize;
let ncols = dims[1] as usize;
@alekrutkowski
alekrutkowski / importDataFromEurostat.M
Last active October 25, 2024 13:46
PoweQuery M example of importing data from Eurostat
let
Source = Csv.Document(Web.Contents("https://ec.europa.eu/eurostat/api/dissemination/sdmx/3.0/data/dataflow/ESTAT" &
"/nama_10_gdp/1.0/*?" & // ← modify dataset
// ↓ modify dimensions and their values
"c[unit]=CP_MEUR&c[na_item]=B1GQ,P3&c[geo]=EU27_2020,EA20" &
"&compress=false&format=csvdata&formatVersion=2.0&" &
"c[TIME_PERIOD]=ge:2021+le:2023"), // ← modify time span
[Delimiter=",",
Encoding=65001, QuoteStyle=QuoteStyle.None]),
PromotedHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
# Code generated with eurodata_codegen on 2024-09-18 16:26:27 (UTC+2:00, Central European Summer Time)
library(magrittr)
library(data.table)
library(eurodata)
library(openxlsx2)
dt__lfsi_emp_a <-
## Link to filtered raw data (TSV):
# https://ec.europa.eu/eurostat/api/dissemination/sdmx/2.1/data/LFSI_EMP_A/.EMP_LFS.T.Y20-64.PC_POP.EU27_2020?format=TSV
## Meaning of the codes in `filters` below:
@alekrutkowski
alekrutkowski / helper_functions.R
Last active November 8, 2024 08:44
ESSPROS social protection expenditure real growth decomposition including early estimates
renameColumns <- function(dt, ...) {
pairs <-
substitute(list(...)) %>%
as.list %>%
tail(-1) %>%
lapply(. %>% as.list %>% tail(-1) %>% rev)
from <-
pairs %>%
sapply(. %>% .[[1]] %>% as.character)
to <-
@alekrutkowski
alekrutkowski / data.table_setnames_extensions.R
Created September 6, 2024 08:23
R functions – convenient extensions of data.table's `setnames` function
library(magrittr)
library(data.table)
setnamesWithArrows <- function(dt, ...) {
pairs <-
substitute(list(...)) %>%
as.list %>%
tail(-1) %>%
lapply(. %>% as.list %>% tail(-1) %>% rev)
from <-
@alekrutkowski
alekrutkowski / namedList.R
Last active August 28, 2024 08:09
R function to avoid the repetitions in situations like `list(first = first, second = second, third = third)`
namedList <- function(...) {
# Capture the variable names as symbols
# and convert symbols to character names
var_names <- as.character(as.list(substitute(list(...)))[-1])
# Create a named list
stats::setNames(mget(var_names, envir = parent.frame()), var_names)
}
### Usage example
@alekrutkowski
alekrutkowski / webR.download.file.R
Created May 6, 2024 07:18
`download.file` function compatible with webR (CORS)
webR.download.file <- function(url, destfile)
download.file(paste0("https://corsproxy.io/?",URLencode(url)),
destfile)
# See https://github.com/r-wasm/webr/issues/252#issuecomment-1690142510