2015-05-17 75 views
-2

我有以下功能:排除行爲NAS在逐列計算

colNames = c(1,4) 
myfun = function(a,b){ 
    test$result = 0.0 
    for (i in colNames) 
    { 
    test$result = test$result + (test[,i] * exp(-a*test[,i+1]) * exp(b*test[,i+2])) 
    } 
    return(test$result) 
} 

我基本上試圖乘在序列3列(由i + 1的執行記錄操作和我+ 2列並將它們與第i列相乘)並將其結果添加到對接下來的3列進行的類似操作中。

但是,我有幾個空值,每當遇到一個空值的test [,i]中的行時,我想從計算中排除它並執行下一個循環。

我的意思是不應該在測試$結果的計算中使用test [,i]中具有空值的行。無論如何要做到這一點?

的樣本數據:

2 1708.637715 21.30199589 1 408.4464296 19.8614872 
1 1708.637715 21.30199589 1 408.4464296 19.8614872 
2 1708.637715 21.30199589 1 408.4464296 19.8614872 
1 1708.637715 21.30199589 1 408.4464296 19.8614872 
6 1708.637715 21.30199589 NA 408.4464296 19.8614872 
0 1708.637715 21.30199589 NA 408.4464296 19.8614872 

我的第一次迭代應該會正常運行,但在接下來的迭代中僅列1至4必須在除了使用

請幫

回答

1

您只需必須在進入循環之前用NA過濾掉任何行。要做到這一點的代碼如下:

test <- test[!apply(is.na(test), 1, any),] 

所以後來如果改變功能:

new.myfun = function(a,b){ 
    test <- test[!apply(is.na(test), 1, any),] 
    test$result = 0.0 
    for (i in colNames) 
    { 
    test$result = test$result + (test[,i] * exp(-a*test[,i+1]) * exp(b*test[,i+2])) 
    } 
    return(test$result) 
} 

new.myfun(1,1) 

隨着輸出:

[1] 1.736616e-169 1.736616e-169 1.736616e-169 1.736616e-169 

這是希望你想要什麼實現。


您可以通過行明確迭代(或使用應用功能):

new.myfun = function(a,b){ 

check.for.na <- function(x,y,z, a, b) { 
    if(any(is.na(x), is.na(y), is.na(z))){ 
    return(0) 
    } 
    return(x*exp(-a*y)*exp(-b*z)) 
} 

result = rep(0, length(test)) 
for (ROW in 1:length(test)){ 
    for (i in colNames) 
    { 
    check_here_for_na <- check.for.na(test[ROW,i], test[ROW,i+1], test[ROW,i+2], a, b) 
    result[ROW] = result[ROW] + check_here_for_na 
    } 
} 
return(result) 
} 

new.myfun(1,1) 
+0

我讓你在說什麼。但我還是想繁殖和使用非NA列我的計算。在我的例子中,我仍然想爲行5和行6應用函數,但是對於列1,2,3(沒有NAs),並且由於它們具有NA值而省略列4,5和列。 – uncut1208

+1

難道你不能在函數中對它進行編碼,然後遍歷它rowise? (你可以使用apply函數),但只是爲了說清楚我剛剛使用了for循環.....請參閱我的編輯 – chappers

+0

謝謝。我最初編寫的代碼實現它rowwise但我的數據是巨大的5000列和約100萬行。所以我轉移到列操作來應用該功能。但我仍然會按照你的建議檢查執行時間 – uncut1208