Create a column based on the last non-null value of another column from different groups

I would like to create a column based on the last non-null value of another column from different ids (groups).

For example, from possession of these dice:

enter image description here

Obtained through:

structure(list(id = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 
3, 3, 4, 4, 4, 4, 4), select = c(1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 
3, 5, 0, 0, 0, 2, 0, 0, 0, 0)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -20L))

I would like to get something like:

enter image description here

I appreciate any help.

>Solution :

Grab the last() value .by= each group, after only looking at values which are != 0:

library(dplyr)

dat %>%
    mutate(result = last(select[select != 0]), .by=id)
### A tibble: 20 × 3
##      id select result
##   <dbl>  <dbl>  <dbl>
## 1     1      1      2
## 2     1      0      2
## 3     1      0      2
## 4     1      2      2
## 5     1      0      2
## 6     2      0      1
## 7     2      0      1
## 8     2      0      1
## 9     2      1      1
##10     2      0      1
##11     3      3      5
##12     3      5      5
##13     3      0      5
##14     3      0      5
##15     3      0      5
##16     4      2      2
##17     4      0      2
##18     4      0      2
##19     4      0      2
##20     4      0      2

Leave a Reply