Ignore security check when using specified names

DT<-data.table(a=1,b=2,a=3) DT # aba #1: 1 2 3 setnames(DT,"b","c") #Error in setnames(DT, "b", "c") : # 'old' is character but there are duplicate column names: a 

In the above example, you can see that I want to change the column heading, which is not duplicated, but setnames prevents me from doing this. Is there a way to ignore validation, since the column heading I'm modifying is not duplicated?

+7
r data.table
source share
2 answers

+1 Now fixed in v1.8.11. From NEWS :

setnames (DT, "oldname", "newname") no longer complain about duplicating column names in DT if the name is unique and unambiguous. Thanks to wet feet for highlighting.

+8
source share

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.

+4
source share

All Articles