匹é…两列并给出一个输出,使得如果一列具有æŸä¸ªå€¼ï¼Œå¦ä¸€åˆ—具有NA,则它å映R中的值

时间:2017-06-13 04:33:19

标签: r

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

以上是两列,R中的所需输出输出应该是,如果两列都匹é…,它应该给出"匹é…",如果一列有匹é…而å¦ä¸€åˆ—有NA,它应该ä»æ‰“å°ï¼†ï¼ƒ34;匹é…"。但如果它们都是NA,则应将其打å°ä¸ºNA

2 个答案:

答案 0 :(得分:2)

我们å¯ä»¥ä½¿ç”¨pmax

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

或coalesce

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

æ•°æ®

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")

答案 1 :(得分: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>