I have a script returning a data.table
which will contain a set of columns. I'd like to rename some of these columns, but setnames
breaks if not all are present. Is there any way to 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 like setnames(..., allow=T)
would be ideal.
Edit: Filed this as a FR on Github.
As of data.table
v1.12.0 (13 Jan 2019), this is an argument to setnames
:
setnames(..., skip_absent=TRUE) # FALSE by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With