1

I have a data.frame with NA's and I would like to coalesce them relative to their location in the data.frame and finally if all in a row are missing then use some arbitray value I provide :

I've come up with this code which works recursively on the supplied ... argument. I'm pretty sure there is a better idea though, or a built in function.

coalesce <- function(x,...) {

  fillerList <- list(...)
    y <- try(y <- unlist(..1))
    if(class(y)=="try-error" | length(y)==0L) {
        x <- x 
    }
    else if(length(y)==1L) {
     x[is.na(x)] <- y
    }
    else {
     x[is.na(x)] <- y[is.na(x)]
    }
    # recursion
    if(length(fillerList)-1L<=0L) {return(x)}
    else {return(coalesce(x,fillerList[-1]))}
}

1 Answers1

1

I have a ready-to-use implementation called coalesce.na in my misc package. Install using

library(devtools)
install_github("krlmlr/kimisc")

and use it just like in your implementation.

As seen in my answer to the linked question, it is competitive to other solutions in terms of runtime and offers extra features such as allowing to use vectors of different length.

Community
  • 1
  • 1
krlmlr
  • 25,056
  • 14
  • 120
  • 217