Skip to content

Instantly share code, notes, and snippets.

@AbdouSeck
Created October 3, 2018 00:03
Show Gist options
  • Save AbdouSeck/47762c0f4ef2292345e1728fbbbbc3ad to your computer and use it in GitHub Desktop.
Save AbdouSeck/47762c0f4ef2292345e1728fbbbbc3ad to your computer and use it in GitHub Desktop.
R code to provide an answer to stackoverflow question at https://stackoverflow.com/q/52613778/3135417
# https://stackoverflow.com/q/52613778/3135417
# Function to keep track of diff changes along the V1 column
get_ids <- function(x) {
vrle <- rle(cummin(x))$lengths
rep(1:length(vrle), vrle)
}
# Thesis data
thesis <- data.frame(V1=c(8628, 8626, 8624, 8622, 8620, 8618,
8576, 8574, 8572, 8570, 8568, 8566,
8422, 8420, 8418),
V2=c(0.0191929, 0.0383858, 0.0575787,
0.0767716, 0.0959645, 0.1151574,
0.1343503, 0.1535432, 0.1727361,
0.191929, 0.2111219, 0.2303148, 0.2495077,
0.2687006, 0.2878935))
# Split the original data.frame.
# Use the get_ids function to segment the V1 column.
# If the diff changes stop decrementing by 2, then the id value is incremented
chunks <- split(thesis, get_ids(c(-2, diff(thesis$V1))))
# Filtering for sub data.frames with more than 2 rows
Filter(function(df) nrow(df) > 2, chunks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment