r - Using data.table::setnames() when some column names might not be present -
i have script returning data.table contain set of columns. i'd rename of these columns, setnames breaks if not present. there way rename without looping+error catching or intersecting against existing names?
iris.dt <- data.table(iris) # first time works fine setnames(iris.dt, c("sepal.length", "sepal.width"), c("length", "width")) # second time fails because columns no longer exist setnames(iris.dt, c("sepal.length", "sepal.width"), c("length", "width")) # error in setnames(iris.dt, c("sepal.length", "sepal.width"), c("length", # :items of 'old' not found in column names: sepal.length,sepal.width something setnames(..., allow=t) ideal.
edit: filed fr on github.
this revised setnames function did 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) } }
Comments
Post a Comment