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

How to perform a rolling coalesce of columns in R

I’ve got a dataframe like this one:

stage1 stage2 stage3 stage4
a        NA     b      c
NA       d      NA     e
NA       NA     f      g
NA       NA     NA     h

Where each column is a stage from a process. What I want to do is to coalesce each column based on the previous columns:

stage1 stage2 stage3 stage4 
a        a      a      a
NA       d      d      d
NA       NA     f      f
NA       NA     NA     h

The actual values don’t really matter, this could also be a logical dataframe, where each string from the output is TRUE and each NA is FALSE .

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

I’ve written this function that lets me coalesce through a selection of columns:

coacross <- function(...) {
  coalesce(!!!across(...))
}

df <- df %>%
  mutate(total_stages = coacross(everything()))

Which basically creates stage4 column of my desired output. Is there any way to iteratively run this, ideally without a for loop? So I can do the same for stage2 and stage3? Else, is there another way to do this?

Thanks a lot.

Edit:

This works:

for(col in names(df %>% select(-stage1))){
  print(col)
  df = df %>%
    mutate({{col}} := coacross(stage1:{{col}}))
  
}

But any more elegant solutions are greatly appreciated

>Solution :

You can use across() with an assist from cur_column():

library(dplyr)

df %>%
  mutate(across(everything(), \(x) coacross(stage1:cur_column())))
  stage1 stage2 stage3 stage4
1      a      a      a      a
2   <NA>      d      d      d
3   <NA>   <NA>      f      f
4   <NA>   <NA>   <NA>      h
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