0

How can I add an index variable to a data frame in R that increments by 1 with each new value? If I have a variable var, as in the example below, how can I create the variable index (preferably using tidyverse)?

library(tidyverse)
df <- tibble(  var = c(1, 1, 3, 4, 4, 6))
df
#> # A tibble: 6 x 1
#>     var
#>   <dbl>
#> 1     1
#> 2     1
#> 3     3
#> 4     4
#> 5     4
#> 6     6

desired_output <- tibble(
  var = c(1, 1, 3, 4, 4, 6),
  index = c(1, 1, 2, 3, 3, 4)
)
desired_output
#> # A tibble: 6 x 2
#>     var index
#>   <dbl> <dbl>
#> 1     1     1
#> 2     1     1
#> 3     3     2
#> 4     4     3
#> 5     4     3
#> 6     6     4
captain
  • 543
  • 1
  • 3
  • 20

1 Answers1

1

Make it a factor and then convert it to numeric.

df %>% mutate(index = as.integer(factor(var)))

#> # A tibble: 6 x 2
#>     var index
#>   <dbl> <int>
#> 1     1     1
#> 2     1     1
#> 3     3     2
#> 4     4     3
#> 5     4     3
#> 6     6     4
Edo
  • 7,567
  • 2
  • 9
  • 19