Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use coalesce rowise?

Tags:

r

dplyr

I have this tibble

library(tidyverse)
data_frame(first = c("a", NA, "b"),
           second = c(NA, "b", NA),
           third = c("a", NA, NA))

I would like to use coalesce() row-wise to grab only values that are not NA.

The desired output would be a vector of the first non NA values that we can find inspecting the dataframe rowwise from left to righ

[1] "a" "b" "b"
like image 421
Dambo Avatar asked Dec 06 '25 13:12

Dambo


1 Answers

Use do.call with coalesce:

do.call(coalesce, df)
# [1] "a" "b" "b"

do.call passes columns in df to coalesce in order and thus equivalent to coalesce(df$first, df$second, df$third).


df <- data_frame(
    first = c("a", NA, "b"),
    second = c(NA, "b", NA),
    third = c("a", NA, NA)
)
like image 53
Psidom Avatar answered Dec 08 '25 07:12

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!