Skip to main content

Python implementations of common R base functions

Project description

rfuns

rfuns is a Python package providing implementations of common base R functions, adapted for Python with 0-based indexing and vectorisation support. This was mainly built to address my own desire to use these functions in exactly the way I would use them in R, but without calling out to an R session. All of these are implemented in Python without external/non-standard dependencies.

This is not intended to be used in production, and makes no guarantees about performance - this is purely for ergonomics of someone who usually writes code in R, but is using Python.

See this blog post for more info.

Installation

Install with uv:

uv add rfuns

Or with pip:

pip install rfuns

Important notes

All indexing is 0-based, unlike R's 1-based system. Vectorisation is opt-in using the vec() function or @_vec decorator on your own functions. Some functions differ from standard Python equivalents to match R behavior, such as setdiff preserving order from the first argument.

Examples

Trim whitespace from strings:

from rfuns import trimws
trimws(["  hello  ", "world "])
# ['hello', 'world']

Split strings:

from rfuns import strsplit
strsplit("these words are split", " ") 
# ["these", "words", "are", "split"]

Find indices of True values:

from rfuns import which
which([False, True, False, True])
# [1, 3]

Find indices where vector equals a value:

from rfuns import which, vec
x = vec(['a', 'b', 'c', 'b'])
which(x == 'b')
# [1, 3]

(note that since Python is not vectorised, a simple == between a list and a value is False, so the list is wrapped in vec() which implements vectorised binary operations)

Generate sequences:

from rfuns import seq, seq_len
seq(2, 5)
# [2, 3, 4, 5]

seq_len(5)
# [0, 1, 2, 3, 4]

Compute set difference preserving order:

set([4, 3, 1, 2]) - set([2, 4])
# {1, 3} 

from rfuns import setdiff
setdiff([4, 3, 1, 2], [2, 4])
# [3, 1]

Apply math functions vectorised:

from rfuns import abs, sqrt
abs([-1, 2, -3])
# [1, 2, 3]

sqrt([81, 9, 4])
# [9.0, 3.0, 2.0]

List files in a directory:

from rfuns import list_files
list_files(".")
# ['file1.txt', 'file2.py']

Implemented functions

The package includes utilities for strings, vectors, math operations, and file handling, working with vector arguments where possible. Functions are designed to work with Python data structures like lists and support manual vectorisation through the vec() wrapper.

Names based on R's dot-separated functions are written with underscores because Python identifiers cannot contain .. Functions marked with are renamed from R-style dot names, and functions marked with are vectorised via the _vec decorator.

Strings

  • nchar(x)
  • nzchar(x)
  • paste(*args, sep=" ", collapse=None)
  • paste0(*args, collapse=None)
  • grepl(pattern, x, ignore_case=False, fixed=False)
  • grep(pattern, x, ignore_case=False, fixed=False, value=False, invert=False)
  • gsub(pattern, replacement, x, ignore_case=False, fixed=False)
  • sub(pattern, replacement, x, ignore_case=False, fixed=False)
  • trimws(x, which="both", whitespace=r"[ \t\r\n]")
  • toupper(x)
  • tolower(x)
  • startsWith(x, prefix)
  • endsWith(x, suffix)
  • strsplit(x, split, fixed=False)
  • substr(x, start, stop)
  • chartr(old, new, x)
  • formatC(x, digits=6, format="g", width=None)

Vectors

  • which(x)
  • which_min(x)
  • which_max(x)
  • diff(x, lag=1)
  • cumsum(x)
  • cumprod(x)
  • cummax(x)
  • cummin(x)
  • rev(x)
  • duplicated(x)
  • setdiff(x, y)
  • intersect(x, y)
  • union(x, y)
  • unique(x)
  • seq_along(x)
  • seq_len(n)
  • seq(from_=0, to=None, by=None, length_out=None) (from is a reserved keyword)
  • sign(x)
  • r_range(x) (renamed to not conflict with range())

Math

  • sign(x)
  • trunc(x)
  • ceiling(x)
  • floor(x)
  • sqrt(x)
  • log(x, base=None)
  • log2(x)
  • log10(x)
  • exp(x)
  • abs(x)
  • var(x, na_rm=False)
  • sd(x, na_rm=False)
  • mean(x, na_rm=False)
  • median(x, na_rm=False)
  • quantile(x, probs=None, na_rm=False)
  • scale(x, center=True, scale_=True)
  • round(x, digits=0)

Files

  • list_files(path=".", pattern=None, all_files=False, full_names=False, recursive=False, ignore_case=False, include_dirs=False, no_dot=False)
  • file_exists(path)
  • dir_exists(path)
  • basename(path)
  • dirname(path)
  • file_path(*args)

Table

  • table(x)
  • prop_table(x)
  • margin_table(x)

Functional

  • lapply(x, func)
  • sapply(x, func)
  • vapply(x, func, expected_type)
  • tapply(x, index, func)
  • rapply(x, func)
  • Filter(func, x)
  • Map(func, *args)
  • Reduce(func, x, init=None, accumulate=False)

Inspect

  • head(x, n=6)
  • tail(x, n=6)
  • length(x)
  • nrow(x)
  • ncol(x)
  • dim(x)
  • summary(x)
  • rstr(x) (renamed to not conflict with str())

Utils

  • vec(x)

Development

The repository includes a Makefile for common tasks.

  • make install installs the package in editable mode with dev dependencies.
  • make test runs pytest on tests/.
  • make test-r runs pytest --r-check and compares rfuns outputs against R when available.
  • make lint runs ruff on rfuns/ and tests/.
  • make format formats code with ruff.
  • make clean removes build artifacts and caches.
  • make repl starts a Python REPL using uv.

R-backed comparison tests use rpy2 and are only run when rpy2 and R are available.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rfuns-0.1.0.tar.gz (20.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rfuns-0.1.0-py3-none-any.whl (21.8 kB view details)

Uploaded Python 3

File details

Details for the file rfuns-0.1.0.tar.gz.

File metadata

  • Download URL: rfuns-0.1.0.tar.gz
  • Upload date:
  • Size: 20.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for rfuns-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2c4171137f3099fb9b428aa9ee82fad7b0a8d0f1fc4758a11a0fa38e1642ca2d
MD5 459fc00e367f972a2b80b4aeb540e8a2
BLAKE2b-256 3a974d4e7fae1047f203bf717f876bbcfa5cf3c6c47365b37db16110b388c74b

See more details on using hashes here.

File details

Details for the file rfuns-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: rfuns-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 21.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for rfuns-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2efc184f25c5eb63abf1273b27fc0c7c5bdfecc59383d0580414de93a9619824
MD5 9f53ab9739806e3d0574f3a0769438bf
BLAKE2b-256 cc1806d157f93e1bf8a357fa23d857ff022d381fb2e342583f897301b14d1062

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page