Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To filter out rows in the year column that have consecutive values for each individual ID in R, you can use the following code:

library(dplyr)

# Create example data frame
df <- data.frame(ID = c(1, 1, 1, 2, 2, 2),
                 year = c(2018, 2019, 2020, 2018, 2019, 2021))

# Filter out consecutive years for each ID
df %>%
  arrange(ID, year) %>%
  group_by(ID) %>%
  filter(year - lag(year) != 1)

In this code, we use the arrange() function from dplyr to sort the data by ID and year. We then group the data by ID using the group_by() function, and filter out any rows where the difference between the year and the lagged year (i.e., the year in the previous row for that ID) is not equal to 1. This ensures that we only keep rows where the year is not consecutive for that individual ID.