Skip to content

Instantly share code, notes, and snippets.

@alekrutkowski
Created September 6, 2024 08:23
Show Gist options
  • Save alekrutkowski/575253247849d20914addac01d934c4b to your computer and use it in GitHub Desktop.
Save alekrutkowski/575253247849d20914addac01d934c4b to your computer and use it in GitHub Desktop.
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 <-
pairs %>%
sapply(. %>% .[[1]] %>% as.character)
to <-
pairs %>%
sapply(. %>% .[[2]] %>% as.character)
setnames(dt, from, to)
}
setnamesWithFunction <- function(dt, FUN)
setnames(dt,
colnames(dt),
colnames(dt) %>% sapply(FUN))
# ### Usage examples
#
# > x <- data.table(a = 1, b = 2)
#
# > x %>% setnamesWithArrows(a -> Aa, b -> bB) %>% print()
#
# Aa bB
# <num> <num>
# 1: 1 2
#
# > x %>% setnamesWithFunction(toupper) %>% print()
#
# AA BB
# <num> <num>
# 1: 1 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment