Manipulate objects by their names
OTHER License
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
{namer}
is a tiny r package containing convenience functions for manipulating
objects by their names. Using these functions makes your code easier to read,
and reduces duplication:
library(namer)
vec <- c(One = 1, Two = 2, Three = 3, Four = 4)
# Base R:
vec[startsWith(names(vec), "T")]
# Clearer:
vec |> named_starting("T")
# Base R:
some_names <- names(vec) %in% c("Two", "Three")
names(vec)[some_names] <- tolower(names(vec)[some_names])
# Clearer:
vec |> rename_in(c("Two", "Three"), tolower)
# Base R:
vec[sort(names(vec))]
# Clearer:
vec |> sort_by_name()
Functions that start with named
return a subset of the original
object:
vec <- c(One = 1, Two = 2, Three = 3, Four = 4)
vec |> named_in(c("Two", "Three", "Non-existent"))
vec |> named_starting("T")
vec |> named_like("[A-Z].*e$")
sort_by_name()
sorts object by name:
sort_by_name(vec)
Functions that start with rename
return the object with its
names changed. You can use a named character vector:
vec |> rename_in(c("One", "Two"), c(one = "One", two = "Two"))
Or an unnamed character vector:
vec |> rename_in(c("One", "Two"), c("First", "Second"))
Or a function:
vec |> rename_all(tolower)
vec |> rename_starting("T", tolower)
Or you can use a one-sided formula, as in purrr:
vec |> rename_in(c("One", "Two"), ~paste(.x, 1:2, sep = "."))
Or use a regular expression with rename_gsub
:
vec |> rename_gsub("[aeiou]", "e")
Or match names from old to new with rename_lookup
:
df <- data.frame(
old = c("One", "Two", "Three", "Four"),
new = c("A", "B", "C", "D")
)
vec |> rename_lookup(df$old, df$new)
You can install from R-universe:
install.packages("namer", repos = c("https://hughjonesd.r-universe.dev",
"https://cloud.r-project.org"))
Or install the development version from GitHub:
# install.packages("remotes")
remotes::install_github("hughjonesd/namer")