Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

Dplyr: subset rows with first observation after a given occurence

$
0
0

I am trying to accomplish the following:

1) group data by id

2) remove any rows after '3' occurs.

3) find the closest '1','2' or NA that precedes '3' and only keep that row.

My data:

data <- data.frame(
id=c(1,1,1,1,1, 2,2,2,2, 3,3,3), 
a=c(NA,1,2,3,3, NA,3,2,3, 1,5,3))

Desired output:

desired <- data.frame(
id=c(1,2,3), a=c(2,NA,1))

For steps 1-2, I have tried:

data %>% group_by(id) %>% slice(if(first(a) == 3))

but that seems quite off.

Thank you.


Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>