0

I have the following dataset:

Municipalities   Year   Emissions
Adamantina       2010       540
Adamantina       2011       543
Adamantina       2012       580
Adolfo           2010       410
Adolfo           2011       411
Adolfo           2012       432

I would like to assign an ID to each observation having the same Municipalitie name ranging from 1 to n. This would result in the following table:

Municipalities   Year   Emissions   id
Adamantina       2010       540      1
Adamantina       2011       543      1
Adamantina       2012       580      1
Adolfo           2010       410      2
Adolfo           2011       411      2
Adolfo           2012       432      2

How can I do this ? Thanks.

phill
  • 95
  • 2
  • 10

1 Answers1

0

Use data.table. Following code assumes your dataframe is named df:

library(data.table)
setDT(df)[, id := .GRP, by = Municipalities]
sumshyftw
  • 1,111
  • 6
  • 14