How can I combine rows within the same data frame in R (based on duplicate values under a specific column)?

后端 未结 4 1335
小鲜肉
小鲜肉 2021-01-07 03:39

Sample of 2 (made-up) example rows in df:

userid   facultyid  courseid schoolid
167       265        NA       1678  
167       71111      301      NA
         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-07 04:33

    # initialize a vector that will contain row numbers which should be erased
    rows.to.erase <- c()
    
    # loop over the rows, starting from top
    for(i in 1:(nrow(dat)-1)) {
      if(dat$userid[i] == dat$userid[i+1]) {
        # loop over columns to recuperate data when a NA is present
        for(j in 2:4) {
          if(is.na(dat[i,j]))
            dat[i,j] <- dat[i+1,j]
        }
        rows.to.erase <- append(rows.to.erase, i+1)
      }
    }
    
    dat.clean <- dat[-rows.to.erase,]
    dat.clean
    #   userid facultyid courseid schoolid
    # 1    167       265      301     1678
    

提交回复
热议问题