Creating a dummy variable in R that indicates whether an ID is subsequently duplicated

Viewed 42

I am working with a longitudinal dataset of children who leave foster care, and I want to analyze the factors that lead to subsequent reentry (similar to readmission rates/analyses in healthcare). My data is currently in the following format:

> df1
  ID Year
1 A1 2007
2 B3 2007
3 B3 2009
4 C6 2000
5 C6 2007
6 C6 2010

I am looking to create a dummy variable that would indicate whether each ID subsequently shows up again in the dataset. For example:

> df2
  ID Year ReEnters
1 A1 2007        0
2 B3 2007        1
3 B3 2009        0
4 C6 2000        1
5 C6 2007        1
6 C6 2010        0

Using, table(ID), I've been able to label an ID as having a duplicate (i.e., any ID that appears in the table as having a frequency > 1), but as seen above I want to make sure that the final observation of each duplicated ID has a value of 0. In other words, is there a way to label a row as a duplicate, but not the last time it appears?

Thanks!

1 Answers

We could use duplicated

df1$ReEnters <- +(duplicated(df1$ID, fromLast = TRUE))

-output

df1
#  ID Year ReEnters
#1 A1 2007        0
#2 B3 2007        1
#3 B3 2009        0
#4 C6 2000        1
#5 C6 2007        1
#6 C6 2010        0

data

df1 <- structure(list(ID = c("A1", "B3", "B3", "C6", "C6", "C6"), Year = c(2007L, 
2007L, 2009L, 2000L, 2007L, 2010L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))
Related