'Create an ID (row number) column
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
Solution 1:[1]
Two tidyverse alternatives (using sgibb's example data):
tibble::rowid_to_column(d, "ID")
which gives:
ID V1 V2 1 1 23 45 2 2 45 45 3 3 56 67
Or:
dplyr::mutate(d, ID = row_number())
which gives:
V1 V2 ID 1 23 45 1 2 45 45 2 3 56 67 3
As you can see, the rowid_to_column-function adds the new column in front of the other ones while the mutate&row_number()-combo adds the new column after the others.
And another base R alternative:
d$ID <- seq_along(d[,1])
Solution 2:[2]
You could also do this using dplyr:
DF <- mutate(DF, id = rownames(DF))
Solution 3:[3]
Many presented their ideas, but I think this is the sortest and simplest code for this task:
data$ID <- 1:nrow(data)
One line. The one and only.
Solution 4:[4]
data.table solution
Easier syntax and much faster
library(data.table)
dt <- data.table(V1=c(23, 45, 56), V2=c(45, 45, 67))
setnames(dt, c("V2", "V3")) # changing column names
dt[, V1 := .I] # Adding ID column
Solution 5:[5]
Hope this will help. Shortest and best way to create ID column is:
dataframe$ID <- seq.int(nrow(dataframe))
Solution 6:[6]
Here is a solution that keeps the dplyr piping format and places id in the first column, which may be preferred.
d %>%
mutate(id = rownames(.)) %>%
select(id, everything())
Solution 7:[7]
If you're starting without named rows in your df, the tidy way is:
df %>%
mutate(id = row_number()) %>%
select(id, everything())
Solution 8:[8]
The function rownames_to_column() moves rownames into a column; found in the tidyverse package (docs).
rownames_to_column(DF, "my_column_name")
Use column_to_rownames() for the reverse operation.
Solution 9:[9]
If your database is not too large this will work
# Load sample data
Dt1 <- tibble(V1=c(23,45,56),V2=c(45,45,67))
# Create Separate Tibble with row numbers
Dt2 <- tibble(id=seq(1:nrow(Dt1)))
# Join together
Dt3 <- cbind(Dt2,Dt1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | WhiskeyGolf |
| Solution 3 | Eric Lino |
| Solution 4 | Jaap |
| Solution 5 | Jaap |
| Solution 6 | Jope |
| Solution 7 | |
| Solution 8 | Tobi Obeck |
| Solution 9 | Harold Henson |
