Created
April 8, 2014 22:59
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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