1
Column1   Column2  Output
Match     Match    Match
Match     NA       Match
NA        NA       NA

The above are two columns and the desired output in R. Output should be,if both column is Match it should give a "Match",if one column has Match and the other has NA, it should still print "Match". But if both of them are NA's it should print it as NA

A.Info
  • 107
  • 7
  • @Henrik glad you noticed that I particularly asked how to use coalesce(Which I actually didn't). We had many more ways which were not listed on your claimed duplicate question. – A.Info Jun 13 '17 at 12:01

2 Answers2

2

We can use pmax

df1$Output <- do.call(pmax, c(df1, na.rm = TRUE))
df1$Output
#[1] "Match" "Match" NA    

Or with coalesce from dplyr

library(dplyr)
df1 %>%
    mutate(Output = coalesce(Column1, Column2))
#   Column1 Column2 Output
#1   Match   Match  Match
#2   Match    <NA>  Match
#3    <NA>    <NA>   <NA>

data

df1 <- structure(list(Column1 = c("Match", "Match", NA), Column2 = c("Match", 
NA, NA)), .Names = c("Column1", "Column2"), row.names = c(NA, 
-3L), class = "data.frame")
akrun
  • 674,427
  • 24
  • 381
  • 486
1
> df=NULL
> df$Column1=c("Match","Match",NA)
> df$Column2=c("Match",NA,NA)
> df=data.frame(df)
> df
  Column1 Column2
1   Match   Match
2   Match    <NA>
3    <NA>    <NA>
> df$Column3=ifelse(is.na(df$Column1)&is.na(df$Column2),NA,"Match")
> df
  Column1 Column2 Column3
1   Match   Match   Match
2   Match    <NA>   Match
3    <NA>    <NA>    <NA>
Ajay Ohri
  • 2,937
  • 3
  • 25
  • 60