bar
是请求的输出,其中包含所需的colnames。在foo
的一个班轮结构中执行此操作的任何方式,而不使用第二个语句,即分别将rn
和V1
重命名为c
和d
建筑?
请注意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)
但如果有任何方法可以在不需要该功能的情况下徘徊。
答案 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