2013-10-11 49 views
1

我有一個數據框與NA的,我想合併它們相對於他們在data.frame中的位置,最後如果所有在一行都丟失,然後使用我提供的一些任意值:Coaoelsce函數在R

我想出這個代碼,遞歸工作所提供的...說法。 我敢肯定有一個更好的主意,雖然,或者一個內置的功能。

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]))} 
} 
+3

請重複舉例。你想要的輸出的例子也是有幫助的。 –

+1

[這](http://stackoverflow.com/questions/19253820/how-to-implement-coalesce-efficiently-in-r)最近的問題? –

回答

1

我有一個現成的使用實施my misc package稱爲coalesce.na。使用安裝

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

並使用它就像在您的實施。

my answer to the linked question看到的,它是在運行時的其他方面競爭力的解決方案,並提供額外的功能,如允許使用不同長度的載體。