1

What is the easiest way to calculate the number of years per country in R? Please see the sample below. 1) How can I create the "#years" variable? The observation period in the real data is from 1990 to 2010, years are ordered ascendingly.

2) Also, would it be possible to start with "0", instead of "1"?

country year    #years
A       2000    1
A       2001    2
A       2002    3
B       2000    1
B       2001    2
B       2002    3
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
FKG
  • 285
  • 1
  • 4
  • 17

1 Answers1

2

Here is one option with ave from base R

years <- with(df1, ave(year, country, FUN=seq_along))

If we need to start from 0

years <- years -1
df1$years <- years

An option using data.table

library(data.table)
setDT(df1)[, years := seq_len(.N), country]
akrun
  • 874,273
  • 37
  • 540
  • 662