Home > Mobile >  In R, How collect other members of a column based on the value of a specific member in that column?
In R, How collect other members of a column based on the value of a specific member in that column?

Time:04-27

In the following data frame, I want to collect members of B1, where their value in B2 is equal to or more than the value of "a" in B2.

ID  B1  B2
z1  a   2.5
z1  b   1.7
z1  c   170
z1  d   3
y2  a   0
y2  b   0
y2  c   101
y2  d   -30
y3  a   30.8
x3  b   1
x3  c   30.8
x3  d   70.1

so the result would be:

ID  B1  B2
z1  c   170
z1  d   3
y2  b   0
y2  c   101
x3  c   30.8
x3  d   70.1

And then count how many times each of the B1 members (b,c,d) occurred.

CodePudding user response:

df %>%
   group_by(grp=cumsum(B1=='a'))%>%
   filter(B2>=first(B2), B1 != 'a')

# A tibble: 6 x 4
# Groups:   grp [3]
  ID    B1       B2   grp
  <chr> <chr> <dbl> <int>
1 z1    c     170       1
2 z1    d       3       1
3 y2    b       0       2
4 y2    c     101       2
5 x3    c      30.8     3
6 x3    d      70.1     3
  • Related