Darpit Dave
Darpit Dave

Reputation: 71

For each group when is the first occurrence of element 1?

X1 | X2 | Group
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
1 | 4 | 1
0 | 1 | 2
1 | 2 | 2
0 | 1 | 3
0 | 2 | 3
1 | 1 | 4
0 | 1 | 5
0 | 2 | 5
0 | 3 | 5
1 | 4 | 5
1 | 5 | 5
1 | 1 | 6
1 | 2 | 6

Output is:

X2 | Group
1 | 1
2 | 2
0 | 3
1 | 4
1 | 5
1 | 6

Upvotes: 1

Views: 33

Answers (1)

akrun
akrun

Reputation: 887048

After grouping by 'Group', slice the row where the 'X1' is 1 and remove the 'X1'

library(dplyr)
library(tidyr)
df1 %>%
    group_by(Group) %>%
    slice(match(1, X1)) %>%
    ungroup %>%
    select(-X1) %>%
    complete(Group = unique(df1$Group), fill = list(X2 = 0))

Or with summarise

df1 %>%
    group_by(Group) %>%
    summarise(X2 = X2[match(1, X1)]) %>%
    mutate(X2 = replace_na(X2, 0))

data

df1 <- structure(list(X1 = c(1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 
1, 1, 1), X2 = c(1, 2, 3, 4, 1, 2, 1, 2, 1, 1, 2, 3, 4, 5, 1, 
2), Group = c(1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 5L, 5L, 5L, 
5L, 5L, 6L, 6L)), class = "data.frame", row.names = c(NA, -16L
))

Upvotes: 3

Related Questions