One way to do this is to use the function rownames_to_column()
package Tibble.
The example below includes ids for table rows iris
. In this case it creates a column called "rowname".
library(tidyverse)
# só para imprimir melhor
tbl_iris <- as_tibble(iris)
tbl_iris %>%
rownames_to_column()
# A tibble: 150 x 6
rowname Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<chr> <dbl> <dbl> <dbl> <dbl> <fct>
1 1 5.1 3.5 1.4 0.2 setosa
2 2 4.9 3 1.4 0.2 setosa
3 3 4.7 3.2 1.3 0.2 setosa
4 4 4.6 3.1 1.5 0.2 setosa
5 5 5 3.6 1.4 0.2 setosa
6 6 5.4 3.9 1.7 0.4 setosa
7 7 4.6 3.4 1.4 0.3 setosa
8 8 5 3.4 1.5 0.2 setosa
9 9 4.4 2.9 1.4 0.2 setosa
10 10 4.9 3.1 1.5 0.1 setosa
# … with 140 more rows
Another alterative is to create a column with the name you want using mutate()
of dplyr combined with seq_len()
.
tbl_iris %>%
mutate(id = seq_len(nrow(.)))
# A tibble: 150 x 6
Sepal.Length Sepal.Width Petal.Length Petal.Width Species id
<dbl> <dbl> <dbl> <dbl> <fct> <int>
1 5.1 3.5 1.4 0.2 setosa 1
2 4.9 3 1.4 0.2 setosa 2
3 4.7 3.2 1.3 0.2 setosa 3
4 4.6 3.1 1.5 0.2 setosa 4
5 5 3.6 1.4 0.2 setosa 5
6 5.4 3.9 1.7 0.4 setosa 6
7 4.6 3.4 1.4 0.3 setosa 7
8 5 3.4 1.5 0.2 setosa 8
9 4.4 2.9 1.4 0.2 setosa 9
10 4.9 3.1 1.5 0.1 setosa 10
# … with 140 more rows
You’d better use the row_number function()
– Bruno