You can cut out some logic in the call to setnames and smooth it out:
set_names <- function(x, old, new) { i <- match(old, names(x)) new <- new[ !is.na(i) ] i <- i[ !is.na(i) ] invisible(.Call(data.table:::Csetcharvec, attr(x, "names"), as.integer(i), new)) } DT <- data.table(a=1,b=2,a=3) set_names(DT, "b", "c") DT
gives me
> DT aca 1: 1 2 3
Please note that this only changes the name that occurs in the case of duplicates. However, this is not recommended for .Call exported code like this, and you should probably check and ensure that this does not violate your use cases.
Kevin ushey
source share