Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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.

like image 673
Max Ghenis Avatar asked Mar 31 '15 23:03

Max Ghenis


1 Answers

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

setnames(..., skip_absent=TRUE)  # FALSE by default.
like image 97
roussanoff Avatar answered Sep 22 '22 07:09

roussanoff