Ask Your Question
1

How can I use R to filter out rows in the year column that have consecutive values for each individual ID?

asked 2023-06-16 23:37:11 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-16 23:50:01 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-16 23:37:11 +0000

Seen: 9 times

Last updated: Jun 16 '23