Reputation: 1008
I can add a new column to a data.table like this:
DT = data.table(A=sample(3, 10, TRUE),
B=sample(letters[1:3], 10, TRUE), C=sample(10))
DT[, new:=1:10]
But is there a clever way to set it to the start of the data.table? - I know i can do it with setcolorder, but I would like to avoid that.
setcolorder(DT, c("new", "A", "B", "C"))
Upvotes: 6
Views: 4298
Reputation: 375
You could try DT <- data.table(New = c(1:10), DT)
, which will place the new column at the start of your data table.
Upvotes: 5
Reputation: 7164
You could use 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
Upvotes: 2