r - What is the most efficient way to change the case of column names in a data.table? -
sometimes before merging it's useful change case of column names consistency. when working data.frame
pretty straightforward (as outlined here); although same solution works on ``data.table`, throws warning. example,
ran <- rep(34,50) dom <- rep("cat",50) table <- rep("pig", 50) dt <- data.table(ran,dom,table); head(dt) ran dom table 1: 34 cat pig 2: 34 cat pig 3: 34 cat pig 4: 34 cat pig 5: 34 cat pig 6: 34 cat pig ##the data.frame way names(dt) <- toupper(names(dt)) ##the error warning message: in `names<-.data.table`(`*tmp*`, value = c("ran", "dom", "table" : names(x)<-value syntax copies whole table. due <- in r itself. please change setnames(x,old,new) not copy , faster. see help('setnames'). can safely ignore warning if inconvenient change right now. setting options(warn=2) turns warning error, can use traceback() find , change names<- calls.
i've used following workaround avoid error, , it's faster on wide datasets, there data.table
way this?
##the work around upper <- toupper(names(dt)) setnames(dt,upper);head(dt) ran dom table 1: 34 cat pig 2: 34 cat pig 3: 34 cat pig 4: 34 cat pig 5: 34 cat pig 6: 34 cat pig
to give answer, comments say, setnames
data.table
function , data.table
recommended way (as long warning data.table
suggests); e.g.,
setnames(dt,toupper(names(dt)))
not confused setnames
function stats
package! (note upper case n
).
Comments
Post a Comment