Yebelay Berehan
Yebelay Berehan

Reputation: 159

Remove rows after observing some specific row values in group id

I try to filter the group id and remove it after the first observation of sex==2). The data looks like

data<- data.frame( id= c(1, 1, 1, 1,  2, 2, 2, 2,  2, 2, 3, 3, 3,3 ,3,3,4,4,4), sex=c(1,1,2,2,1,1,1,2,2,2,1,1,2,1,1,2,1,2,2))
data
  id sex
  1    1
  1    1
  1    2
  1    2
  2    1
  2    1
  2    1
  2    2
  2    2
  2    2
  3    1
  3    1
  3    2
  3    1
  3    1
  3    2
  4    1
  4    2
  4    2

The desired output

  id sex
  1    1
  1    1
  1    2
  2    1
  2    1
  2    1
  2    2
  3    1
  3    1
  3    2
  3    1
  3    1
  3    2
  4    1
  4    2

I try to

library(dplyr)
data1 <- data %>% filter(type == 1 ) & silec(2))

But I got an error. Please anyone help?

Upvotes: 1

Views: 62

Answers (2)

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8811

Data

data<- data.frame( id= c(1, 1, 1, 1,  2, 2, 2, 2,  2, 2, 3, 3, 3,3 ,3,3,4,4,4), sex=c(1,1,2,2,1,1,1,2,2,2,1,1,2,1,1,2,1,2,2))

Code

data %>% 
  #Grouping by id
  group_by(id) %>% 
  #Filter sex = 1 or the first time sex was equal 2
  filter( sex == 1 | (cumsum(sex == 2) == 1))

Output

# A tibble: 14 x 2
# Groups:   id [4]
      id   sex
   <dbl> <dbl>
 1     1     1
 2     1     1
 3     1     2
 4     2     1
 5     2     1
 6     2     1
 7     2     2
 8     3     1
 9     3     1
10     3     2
11     3     1
12     3     1
13     4     1
14     4     2

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388907

You may create a set of consecutive occurring 1's and 2's in each group. From each group select the rows till you encounter the 1st 2 in it.

library(dplyr)
library(data.table)

data %>%
  group_by(id, grp = ceiling(rleid(sex)/2)) %>%
  slice(seq_len(match(2, sex))) %>%
  ungroup
  select(-grp)

#     id   sex
#   <dbl> <dbl>
# 1     1     1
# 2     1     1
# 3     1     2
# 4     2     1
# 5     2     1
# 6     2     1
# 7     2     2
# 8     3     1
# 9     3     1
#10     3     2
#11     3     1
#12     3     1
#13     3     2
#14     4     1
#15     4     2

Upvotes: 0

Related Questions