如何获取data.table列名的静态向量

时间:2014-07-23 01:26:17

标签: r data.table

我想创建一个data.table对象名称的 immutable 向量,使用setnames后不会改变。例如,我想在这里创建一个mtcars.names版本,它将与"mpg"而不是"miles.per.gallon"相结合:

mtcars.dt <- data.table(mtcars)
(mtcars.names <- names(mtcars.dt))
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
setnames(mtcars.dt, "mpg", "miles.per.gallon")
mtcars.names
 [1] "miles.per.gallon" "cyl"              "disp"             "hp"
 [5] "drat"             "wt"               "qsec"             "vs"
 [9] "am"               "gear"             "carb"

1 个答案:

答案 0 :(得分:3)

mtcars.names <- copy(names(mtcars.dt))
setnames(mtcars.dt, "mpg", "miles.per.gallon")
mtcars.names
## [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
## [11] "carb"