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

Get the first non-null value from selected cells in a row

Good afternoon, friends!

I’m currently performing some calculations in R (df is displayed below). My goal is to display in a new column the first non-null value from selected cells for each row.

My df is:

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

MD <- c(100, 200, 300, 400, 500)
liv <- c(0, 0, 1, 3, 4)
liv2 <- c(6, 2, 0, 4, 5)
liv3 <- c(1, 1, 1, 1, 1)
liv4 <- c(1, 0, 0, 3, 5)
liv5 <- c(0, 2, 7, 9, 10)
df <- data.frame(MD, liv, liv2, liv3, liv4, liv5)

I want to display (in a column called "liv6") the first non-null value from 5 cells (given the data, liv1 = 0, liv2 = 6 , liv3 = 1, liv 4 = 1 and liv5 = 1). The result should be 6. And this calculation should be repeated fro each row in my dataframe..

I do know how to do this in Python, but not in R..

Any help is highly appreciated!

>Solution :

One option with dplyr could be:

df %>%
    rowwise() %>%
    mutate(liv6 = with(rle(c_across(liv:liv5)), values[which.max(values != 0)]))

     MD   liv  liv2  liv3  liv4  liv5  liv6
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1   100     0     6     1     1     0     6
2   200     0     2     1     0     2     2
3   300     1     0     1     0     7     1
4   400     3     4     1     3     9     3
5   500     4     5     1     5    10     4
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