5

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"))
Frank
  • 66,179
  • 8
  • 96
  • 180
Jeppe Olsen
  • 968
  • 8
  • 19
  • 1
    You could combine it all in one line, if lines are your major concern: `setcolorder(DT[, new: = 1:10], c('new', 'A', 'B', 'C'))`, but you'd still be using `setcolorder`.. – KenHBS Sep 15 '17 at 12:44

2 Answers2

4

You could try DT <- data.table(New = c(1:10), DT), which will place the new column at the start of your data table.

Jordan
  • 365
  • 1
  • 10
2

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
KenHBS
  • 6,756
  • 6
  • 37
  • 52