Add an index, possibly by group, at the first place of a data frame or a tibble The name by default is 'index' but can be named. If 'index' already exists, or the given name, the column can be forced to be created, and replace the other one.
add_index(tbl, name_index = "index", start = 1, .force = FALSE)
tibble or data frame
A character string of the name of the column.
integer indicating first index number. 1 by default.
TRUE or FALSE, that parameter indicates whether or not the column is created if already exists. FALSE by default.
A tibble or a data frame containing one extra first column 'index' or any given name.
{
##### Example 1 -------------------------------------------------------------
# add an index for the tibble
add_index(iris, "my_index")
##### Example 2 -------------------------------------------------------------
# add an index for the grouped tibble
library(tidyr)
library(dplyr)
my_tbl <- tibble(iris) %>% group_by(Species) %>% slice(1:3)
add_index(my_tbl, "my_index")
}
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#> # A tibble: 9 × 6
#> my_index Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <int> <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 1 7 3.2 4.7 1.4 versicolor
#> 5 2 6.4 3.2 4.5 1.5 versicolor
#> 6 3 6.9 3.1 4.9 1.5 versicolor
#> 7 1 6.3 3.3 6 2.5 virginica
#> 8 2 5.8 2.7 5.1 1.9 virginica
#> 9 3 7.1 3 5.9 2.1 virginica