R: How to find the first non-zero element in a datframe by group
I have the following dataframe I want to subset this dataset such that I will only have rows between the first record and the the first 1 value in the flag column for each group and if there is no 1, that group should not appear at all. Something like this: I saw some answers at Dplyr : how to find the first-non missing string by groups? But it is for non-missing and I have both non-missing and 0 values. Or in dplyr (same result) Data used: Benchmark Output: Benchmark code: Using dplyr::slice , then the equivalent base R using by . And finally one just for performance, with benchmark. All robust for the case with no Flag==1 in a group. dplyr base base fast benchmark I did the benchmark on @Lebatsnok modified input, that I remodified because the NAs were not properly recognized as such. MKR's and WWW's solutions are not robust for this case, but i left them in the benchmark anyway. data benchmark code A cumsum based solution using dplyr can be as: Data: A solution using dply...