Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading