Merging rows with shared information

前端 未结 4 1173
故里飘歌
故里飘歌 2021-01-07 04:18

I have a data.frame with several rows which come from a merge which are not completely merged:

b <- read.table(text = \"
      ID   Age    Steatosis               


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 04:37

    While I'm sure that it's possible with dplyr or tidyr, here's a data.table solution:

    b <- read.table(text = "
          ID   Age    Steatosis       Mallory Lille_dico Lille_3 Bili.AHHS2cat
                    68 HA-09   16                           5             NA
                    69 HA-09   16   <33% no/occasional             NA             1",
                    na.strings = c("NA", ""))
    
    keycols <- c("ID", "Age")
    library(data.table)
    b_dt <- data.table(b)
    
    filter_nas <- function(x){
      if(all(is.na(x))){
        return(unique(x))
      }
      return(unique(x[!is.na(x)]))
    }
    
    b_dt[, lapply(.SD, filter_nas ), by = mget(keycols)]
    
    
          ID Age Steatosis       Mallory Lille_dico Lille_3 Bili.AHHS2cat
    1: HA-09  16      <33% no/occasional         NA       5             1
    

    Note, this only works if the keys are unique.

提交回复
热议问题