making new variable in R

hi I have data that looks like this:

name date_recorded
al      1/1/2011
al      1/3/2012
al      11/30/2013
al      4/08/2014
al      5/06/2017

I want to add a new column called "prior_records" that tells me how many records are recorded prior to the row in question. it is ordered from oldest date to most recent

name date_recorded prior_records 
al      1/1/2011        0
al      1/3/2012        1
al      11/30/2013      2
al      4/08/2014       3
al      5/06/2017       4

is there an easy way to do this? note I have many people, Al is just one example

Hello,

you are basically implementing a counter by group. So all you have to do is something like

library(dplyr)

Data |>
  group_by(name) |>
  mutate(prior_records = 0:(n() - 1))

Since you have n observations, there would be a length mismatch if you wouldn't correct the sequence by 1 at the end.

Kind regards

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.