【问题标题】:How can I merge two columns in R?如何合并 R 中的两列?
【发布时间】:2021-12-02 16:40:48
【问题描述】:

我的数据框有 2 列与此类似:

a    b

NA   NA
yes  NA
no   NA
yes  NA
NA   yes
NA   no 
NA   NA
Na   yes

我想要的输出是:

ab

NA
yes
no
yes
yes
no
NA
yes

注意:

  • 在原始列中,任何给定行中始终存在 NA。
  • 对于某些行,两列都是 NA

知道如何获得所需的输出吗?

【问题讨论】:

    标签: r dataframe merge na


    【解决方案1】:
    • dplyr::coalesce
    > with(dat, dplyr::coalesce(a, b))
    [1] NA    "yes" "no"  "yes" "yes" "no"  NA    "yes"
    
    • ifelse 用于基础 R
    > with(dat, ifelse(!is.na(a), a, ifelse(!is.na(b), b, NA)))
    [1] NA    "yes" "no"  "yes" "yes" "no"  NA    "yes"
    
    • max.col 用于基础 R
    > dat[cbind(1:nrow(dat), max.col(!is.na(dat)))]
    [1] NA    "yes" "no"  "yes" "yes" "no"  NA    "yes"
    

    【讨论】:

      【解决方案2】:

      使用dplyr你可以把它包装得很整齐:

      library(dplyr)
      
      df %>% rowwise() %>% summarize(ab = max(a,b, na.rm = T))
      

      【讨论】:

        【解决方案3】:
        dat <- data.frame(a = c(NA, "yes", "no", "yes", NA, NA, NA, NA),
                          b = c(NA, NA, NA, NA, "yes", "no", NA, "yes"))
        
        require(tidyverse)
        
        dat %>% 
          rowwise() %>% 
          mutate(ab = max(a,b, na.rm = TRUE))
        

        【讨论】:

          【解决方案4】:

          使用apply:

          > apply(df, 1, max, na.rm=TRUE)
          [1] NA    "yes" "no"  "yes" "yes" "no"  NA    "yes"
          

          作业:

          df$ab <- apply(df, 1, max, na.rm=TRUE)
          

          【讨论】:

            【解决方案5】:
            # Import data: df => data.frame 
            df <- structure(list(a = c(NA, "yes", "no", "yes", NA, NA, NA, NA), 
            b = c(NA, NA, NA, NA, "yes", "no", NA, "yes")), class = "data.frame", row.names = c(NA, 
            -8L))
            
            # Function to coalesce vectors: br_coalesce => function
            br_coalesce <- function(...){
               # Coalesce vectors or data.frames: res => vector
               res <- Reduce(function(x, y) {
                     x <- replace(x, is.na(x), y[is.na(x)])
                  },
                  list(...)
               )
               # Explicitly define returned vectors: character vector => env
               return(res)
            }
            
            # Apply function: character vector / data.frame => stdout(console)
            br_coalesce(df$a, df$b)
            

            Tidyverse 解决方案:

            library(tidyverse)
            df %>% 
               transmute(res = coalesce(a, b))
            

            data.table 解决方案:

            library(data.table)
            fcoalesce(df$a, df$b)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2022-01-15
              • 1970-01-01
              • 2020-10-16
              • 1970-01-01
              • 1970-01-01
              • 2012-03-20
              • 2018-12-07
              相关资源
              最近更新 更多