Using data.table::setnames() when some column names might not be present

This revised setnames function did the trick:

Setnames <- function(x, old, new, allow.absent.cols=F) {
  if (!allow.absent.cols) {
    setnames(x, old, new)
  } else {
    old.intersect <- intersect(old, names(x))
    common.indices <- old %in% old.intersect
    new.intersect <- new[common.indices]
    setnames(x, old.intersect, new.intersect)
  }
}

You can try "one-liner"

library(data.table)
iris.dt <- data.table(iris)

setnames(iris.dt,c("Sepal.Length", "Sepal.Width")[names(iris.dt) %chin% c("Sepal.Length", "Sepal.Width")], c("length", "width")[names(iris.dt) %chin% c("Sepal.Length", "Sepal.Width")])

You can use old and new as input variables.


As of data.table v1.12.0 (13 Jan 2019), this is an argument to setnames:

setnames(..., skip_absent=TRUE)  # FALSE by default.

Tags:

R

Data.Table