0

I have a generalized example data with two columns one is a date and the other is a is an numerical index for the dates. I would like to be able to reset the indexes to all start at 1. Below shows the visually what I would like to accomplish. Thanks for the help.

dateA = c("5/8/2020","5/8/2020", "5/8/2020", "5/9/2020","5/9/2020", "5/9/2020", "5/9/2020", "5/10/2020","5/10/2020", "5/10/2020", "5/11/2020")
varA = c(2,3,4,9,10,11,12,20,21,22,55)
data = data.frame(dateA,varA)
Oringal Index
dateA     varA
5/8/2020  2
5/8/2020  3
5/8/2020  4
5/9/2020  9
5/9/2020  10
5/9/2020  11
5/9/2020  12
5/10/2020 20
5/10/2020 21
5/10/2020 22
5/11/2020 55

Reset Index
dateA     varA
5/8/2020  1
5/8/2020  2
5/8/2020  3
5/9/2020  1
5/9/2020  2
5/9/2020  3
5/9/2020  4
5/10/2020 1
5/10/2020 2
5/10/2020 3
5/11/2020 1
MrClean
  • 1,300
  • 2
  • 12
  • 17

1 Answers1

1

We can use rowid from data.table

library(data.table)
data$varA <- rowid(data$dateA)

Or using data.table syntax

setDT(data)[, varA := rowid(dateA)]

Or with dplyr

library(dplyr)
data %>%
    group_by(dateA) %>%
    mutate(varA = row_number())

Or using base R

data$varA <- with(data, ave(seq_along(dateA), dateA, FUN = seq_along))
akrun
  • 874,273
  • 37
  • 540
  • 662