Created
December 30, 2015 16:36
-
-
Save dmarcelinobr/fc882cc88156c282959a 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]]) | |
| # Usage | |
| 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) | |
| i<-i+1 | |
| } | |
| return(x[[1]]) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment