Wednesday, January 3, 2018

Replace NA value with the last numeric value in each row


replace.NA.with.last.value.in.each.row <- function(dat)
{ 
    ## Purpose: Replace NA value with the last numeric value in each row. 
    ## Arguments:
    ##   dat: a data frame that may have NA in the tail of each row. 
    ## Return: an updated data frame with no NA values. 
    ## Author: Feiming Chen, Date:  3 Jan 2018, 11:34
    ## ________________________________________________

    last.value <- apply(dat, 1, function(x) as.numeric(tail(na.omit(x), 1))) # last numeric value in each row. 

    n <- is.na(dat)
    for (i in 1:nrow(dat)) {
        dat[i, n[i,]] <- last.value[i]
    }

    dat
}
if (F) {                                # Unit Test
    dat <- data.frame(ID=LETTERS[1:5], V1=c(1:4, NA), V2=c(6:7, NA, NA, NA), V3 = c(8, rep(NA, 4)))
    ##   ID V1 V2 V3
    ## 1  A  1  6  8
    ## 2  B  2  7 NA
    ## 3  C  3 NA NA
    ## 4  D  4 NA NA
    ## 5  E NA NA NA
    replace.NA.with.last.value.in.each.row(dat)
    ##   ID V1 V2 V3
    ## 1  A  1  6  8
    ## 2  B  2  7  7
    ## 3  C  3  3  3
    ## 4  D  4  4  4
    ## 5  E NA NA NA
}

No comments:

Post a Comment