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.
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
Asked: 2023-06-16 23:37:11 +0000
Seen: 9 times
Last updated: Jun 16 '23
How can a specific "collection" be filtered from a JSON fetch?
How can the default filter selections be reapplied using TableSorterJS?
How can custom cell filtering be implemented in MUI X?
What is a fast way to locate a distinct value in a spreadsheet without relying on VLOOKUP?
How to make a personalized filter for DataGridPro while looping through a collection of items?
What are the steps for conducting a precise search and filter using sequelize in node.js?
How can I apply a filter to the "Name" Column in a SharePoint Document Library?
In this scenario, what is the method to output the filter array?