Skip to content

Instantly share code, notes, and snippets.

@MrFlick
Created April 8, 2014 22:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrFlick/10205794 to your computer and use it in GitHub Desktop.
Save MrFlick/10205794 to your computer and use it in GitHub Desktop.
Coalesce.R: A coalesce function for R (returns first non-NA value from a list of vectors)
coalesce<-function(...) {
x<-lapply(list(...), function(z) {if (is.factor(z)) as.character(z) else z})
m<-is.na(x[[1]])
i<-2
while(any(m) & i<=length(x)) {
if ( length(x[[i]])==length(x[[1]])) {
x[[1]][m]<-x[[i]][m]
} else if (length(x[[i]])==1) {
x[[1]][m]<-x[[i]]
} else {
stop(paste("length mismatch in argument",i," - found:", length( x[[i]] ),"expected:",length( x[[1]] ) ))
}
m<-is.na(x[[1]])
i<-i+1
}
return(x[[1]])
}
x<-c(1,NA,NA,4,5)
y<-c(NA,22,NA,44,NA)
z<-c(100,200,300,400,500)
coalesce(x,y)
coalesce(x,y,-1)
coalesce(x,y,z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment