0

I have a data frame like this:

      cod  ano partido_prefeito
1  110001 1998             <NA>
2  110001 1999             <NA>
3  110001 2000             <NA>
4  110001 2001              PPB
5  110001 2002              PPB
6  110001 2003              PPB
7  110001 2004              PPB
8  110001 2005              PDT
9  110001 2006              PDT
10 110001 2007              PDT
11 110001 2008              PDT
12 110001 2009              PTN
13 110001 2010              PTN
14 110001 2011              PTN
15 110001 2012              PTN

The data frame contains much more information The same sequence of years for each different cod. What I want to create is a new variable called maybe "dummy_pref" which is 1 when the variable "partido_prefeito" changes, except when is NA and 0 otherwise. Like this:

      cod  ano partido_prefeito dummy_pref
1  110001 1998             <NA>          0
2  110001 1999             <NA>          0
3  110001 2000             <NA>          0
4  110001 2001              PPB          0
5  110001 2002              PPB          0
6  110001 2003              PPB          0
7  110001 2004              PPB          0
8  110001 2005              PDT          1
9  110001 2006              PDT          0
10 110001 2007              PDT          0
11 110001 2008              PDT          0
12 110001 2009              PTN          1
13 110001 2010              PTN          0
14 110001 2011              PTN          0
15 110001 2012              PTN          0

I thought about something using group_by(cod) and then mutate, but I don't know how to call the mutate. It's not a identification, it's a dummy Thanks!

Danilo Imbimbo
  • 207
  • 1
  • 9

0 Answers0