数据开头的新列 table

New column in the start of a data table

我可以像这样向 data.table 添加一个新列:

DT = data.table(A=sample(3, 10, TRUE), 
         B=sample(letters[1:3], 10, TRUE), C=sample(10))

DT[, new:=1:10]

但是有什么巧妙的方法可以将它设置为 data.table 的开头吗? - 我知道我可以用 setcolorder 做到这一点,但我想避免这种情况。

setcolorder(DT, c("new", "A", "B", "C"))

你可以使用 cbind():

DT = data.table(A=sample(3, 10, TRUE), 
                B=sample(letters[1:3], 10, TRUE), C=sample(10))

cbind(new=1:10, DT)
#    new A B  C
# 1:   1 2 b  8
# 2:   2 3 b 10
# 3:   3 1 b  1
# 4:   4 1 a  5
# 5:   5 2 a  6
# 6:   6 3 c  2
# 7:   7 3 a  3
# 8:   8 1 a  4
# 9:   9 1 a  7
#10:  10 3 c  9

您可以尝试 DT <- data.table(New = c(1:10), DT),这会将新列放在数据的开头 table。