Search code examples
rcoalesce

How to use Coalesce function on a dataframe


I tried finding a way to handle NA data but unable to do so, Please assist me on this.

I have below data,

R1 <- c("15515","5156","65656","1566", "2857","8888","65656","1566","65651")
R2 <- c("515","5156.11-","415-","1455-","886","888","777","666","4457")
RC1 <- c("AW","FG","ZA","ZI","","CW","","","")
RC2 <- c("SSSBB","","","ZXXQA","","CQAER","","KKHDY","TTQWW")
RC3 <- c("KKAJDJHW","XVVJAKWA","","","","CDDGAJJA","GGGAJTTD","","BBNMNJJI")
df <- data.frame(R1,R2,RC1,RC2,RC3)

I am using below code to tackle NA among only RC1,RC2 & RC3

df_1$RCC <- with(df_1, coalesce(df_1$RC3,df_1$RC2,df_1$RC1))
df_1

enter image description here

I am unable to fetch data from RC1 & RC2. Need your Kind assistance.


Solution

  • For coalesce to work you need NA's and not blanks. Change the blanks to NA and try :

    library(dplyr)
    
    df[df == ''] <- NA
    df %>% mutate(RCC = coalesce(RC3, RC2, RC1))
    
    #    R1       R2  RC1   RC2      RC3      RCC
    #1 15515      515   AW SSSBB KKAJDJHW KKAJDJHW
    #2  5156 5156.11-   FG  <NA> XVVJAKWA XVVJAKWA
    #3 65656     415-   ZA  <NA>     <NA>       ZA
    #4  1566    1455-   ZI ZXXQA     <NA>    ZXXQA
    #5  2857      886 <NA>  <NA>     <NA>     <NA>
    #6  8888      888   CW CQAER CDDGAJJA CDDGAJJA
    #7 65656      777 <NA>  <NA> GGGAJTTD GGGAJTTD
    #8  1566      666 <NA> KKHDY     <NA>    KKHDY
    #9 65651     4457 <NA> TTQWW BBNMNJJI BBNMNJJI