I need to create a column with unique ID, basically add the row number as an own column. My current data frame looks like this:
V1 V2
1 23 45
2 45 45
3 56 67
How to make it look like this:
V1 V2 V3
1 23 45
2 45 45
3 56 67
? Many thanks
You could also do this using
dplyr
:Two tidyverse alternatives (using sgibb's example data):
which gives:
Or:
which gives:
As you can see, the
rowid_to_column
-function adds the new column in front of the other ones while themutate
&row_number()
-combo adds the new column after the others.And another base R alternative:
Many presented their ideas, but I think this is the sortest and simplest code for this task:
One line. The one and only.
You could use
cbind
:EDIT: Here a comparison of @dacko suggestions.
d$id <- seq_len(nrow(d)
is slightly faster, but the order of the columns is different (id
is the last column; reorder them seems to be slower than usingcbind
):data.table solution
Easier syntax and much faster
Hope this will help. Shortest and best way to create ID column is: