2016-10-12 58 views
0

bar的構建中,在一個班輪中重命名(特定)列名稱是所需的具有該colname的輸出。任何方式在foo的單線結構中執行此操作,而不使用第二種語句,即分別在工程中重命名爲rnV1cd在data.table

請注意,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) 

但是如果有任何方法可以徘徊而不需要該功能。

回答

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 
4

我錯過了什麼嗎?

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