Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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!

like image 223
lenpyspanacb Avatar asked Oct 18 '25 17:10

lenpyspanacb


2 Answers

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
like image 76
tmfmnk Avatar answered Oct 20 '25 06:10

tmfmnk


A Base R solution:

df$liv6 <- apply(df[-1], 1, function(x) x[min(which(x != 0))])

output

df
   MD liv liv2 liv3 liv4 liv5 liv6
1 100   0    6    1    1    0    2
2 200   0    2    1    0    2    2
3 300   1    0    1    0    7    1
4 400   3    4    1    3    9    1
5 500   4    5    1    5   10    1
like image 39
Maël Avatar answered Oct 20 '25 06:10

Maël