Search code examples
rdata.tableauto-increment

adding a record counter to a data.table


I have an existing data.table that I am wanting to add an 'identity' column to.

I know how to add a column e.g:

DT$newCol <- x

However I am struggling to make the new value an auto-incrementing counter from 1 to n.

I would have asked as a comment to this question (data.table "key indices" or "group counter") as it is related, however I don't have enough reputation to comment.

Thanks in advance.


Solution

  • In the spirit of completeness in case someone stumbles across this.

    DT[, newcol := 1:.N] 
    

    is how I solved the problem. Thanks to go @thelatemail and @Simon