I'm working on a database which has information about individual identification (Id
), Date
, Group_id
data = data.frame(Id = 1:6,
Date = as.Date(c("2010-12-28", "2011-01-28", "2011-01-30", "2009-09-01", "2009-09-05", "2012-12-20")),
Group_id = c(1,1,2,3,3,3))
and now I would like to create a new dummy Recurrent
variable that returns 1 if there are previous information about another individual from the same Group_id
and 0 otherwise . My desired output is like this:
Id Date Group_id Recurrent
1 2010-12-28 1 0
2 2011-01-28 1 1
3 2011-01-30 2 0
4 2009-09-01 3 0
5 2009-09-05 3 1
6 2012-12-20 3 1
but I'm quite confused about how to perform that. Can anyone give me a tip on how to do that?
regards!
CodePudding user response:
- Try this
library(dplyr)
data |> mutate(Recurrent = as.numeric(duplicated(Group_id)))
- Output
Id Date Group_id Recurrent
1 1 2010-12-28 1 0
2 2 2011-01-28 1 1
3 3 2011-01-30 2 0
4 4 2009-09-01 3 0
5 5 2009-09-05 3 1
6 6 2012-12-20 3 1