Skip to content

Allow functions in setnames input #3703

@smingerson

Description

@smingerson

Below are two proposed enhancements to setnames(), contrasted with current alternatives. I think they coincide with data.table's desire to provide concise syntax. I'd be happy to work on a PR for either or both of these if you think they are worth adding.

library(data.table)

dt <- data.table(a = 1:2, b = c('fa', 'fb'), d = NA, yes = 1, no = 0)
dt
#>    a  b  d yes no
#> 1: 1 fa NA   1  0
#> 2: 2 fb NA   1  0

setnames(dt, c('A', 'B', 'D', 'YES', 'NO'))[]
#>    A  B  D YES NO
#> 1: 1 fa NA   1  0
#> 2: 2 fb NA   1  0
# Offer  `setnames(dt, function)` as an option to rename all using a function.
# This would be `setnames(dt, toupper)`
# Right now, I would do setnames(dt, toupper(names(dt))) -- not much more verbose,
# but I'd have to type descriptive table names twice.

to_change <- c("YES", "NO")
setnames(dt, to_change, paste0("IND_", to_change))[]
#>    A  B  D IND_YES IND_NO
#> 1: 1 fa NA       1      0
#> 2: 2 fb NA       1      0
# Offer `setnames(dt, patterns(...), function)` as an option to rename a subset.
# This would be `setnames(dt, patterns("[A-z]{3}), function(x) paste0("IND_", x))`.
# In this simple example, the proposed syntax doesn't have much benefit, but in
# more complicated cases I think it would be more concise than
# to_change <- grep(pattern,names(dt)))
# setnames(dt, to_change, renaming_function(to_change))

Created on 2019-07-13 by the reprex package (v0.2.1)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions