I have a data frame like this:
df <- data.frame(x = c(0:20), y = c(50:70),
m = c(0, 0, 0, 0, -1, 0, 0, 1, 0, 0, -1, 0 ,0 , -1, 0, 0, 1, 0, 0, -1, 0))
I would like to create subsets defined by a sequence of values in column 'm':
A sequence should start and end with m == -1, and there has to be a 1 between the start and finish -1. Each subset then includes all rows between the start and end.
For example, one of the subsets from the data above would look like:
Subset1 <- data.frame(x = c(4:10), y = c(54:60), m = c(-1, 0, 0, 1, 0, 0, -1))
# x y m
# 1 4 54 -1 # starts with -1
# 2 5 55 0
# 3 6 56 0
# 4 7 57 1 # contains a 1
# 5 8 58 0
# 6 9 59 0
# 7 10 60 -1 # ends with -1
I have been trying a lot and I can't figure out how to do it. I have tried with mapply or for loops, but always I'm stuck when it comes to set up the pattern, since both ends of the pattern are the same.
For instance, with mapply, I've done:
List_subsets <- mapply(function(i, j, z) df[i:j:z, , drop = FALSE], -1, 1, -1,
SIMPLIFY = FALSE)
But of course, I always get the
# error: In i:j:z : numerical expression has 3 elements: only the first used
Do you know if that's possible and could you help me out? I would really appreciate your input, since I'm very new to R and it's very challenging for me.
Thanks a lot in advance!