在构造data.table

时间:2016-10-12 22:12:03

标签: r data.table

bar是请求的输出,其中包含所需的colnames。在foo的一个班轮结构中执行此操作的任何方式,而不使用第二个语句,即分别将rnV1重命名为cd建筑?

请注意list("s1" = 1, "s2" = 2)必须保持不变。

bar是所需的输出:

   a   b   c  d
1: abc bcd s1 1
2: abc bcd s2 2

foo模仿bar

   a   b   rn  V1
1: abc bcd s1  1
2: abc bcd s2  2

MWE脚本:

library(data.table)
bar <- data.table(a = "abc", b = "bcd", c = c("s1", "s2"), d = 1:2)
print("bar:")
print(bar)
foo <- data.table(a = "abc", b = "bcd",
                  data.matrix(list("s1" = 1,
                                   "s2" = 2)), keep.rownames = T)
# colnames(foo) <- c("a", "b", "c", "d")  # without using a second statement like this
print("foo:")
print(foo)

PS:我做的解决方法是定义一个reformat函数,例如

reformat <- function(dt) {
  colnames(dt) <- c("a", "b", "c", "d")
  return(dt)
}
foo <- reformat(data.table(a = "abc", b = "bcd",
                           data.matrix(list("s1" = 1,
                                            "s2" = 2)), keep.rownames = T))
print(foo)

但如果有任何方法可以在不需要该功能的情况下徘徊。

2 个答案:

答案 0 :(得分:4)

我错过了什么吗?

setnames(foo, old = c("c", "d"), new = c("rn", "V1"))

答案 1 :(得分:3)

data.table已经具有重命名列而不复制data.table的功能。

你是否喜欢这样的事情?

setnames(foo <- data.table(a = "abc", b = "bcd", 
                           data.matrix(list("s1" = 1, "s2" = 2)), 
                           keep.rownames = TRUE),
         c("a", "b", "c", "d"))
print(foo)
     a   b  c d
1: abc bcd s1 1
2: abc bcd s2 2