2015-07-12 124 views
0

我有以下一個R函數返回來自R函數的值

pa <- function(data){ 

    if (unique(data$bundles_product_id) == 'B0000DJX70'){ 
    print ('B0000DJX70') 
    return(NA) 
    } 
    # ... some code 

} 數據是這樣的:

1 422 B0000DJX70 14 B00020LXYA 32.33071 55.93000 
2 423 B0000DJX70 15 B00020LXYA 32.10714 53.74429 
3 424 B0000DJX70 16 B00020LXYA 30.45429 53.08143 
4 425 B0000DJX70 17 B00020LXYA 31.82214 50.21000 
5 426 B0000DJX70 18 B00020LXYA 33.01727 49.98429 
6 427 B0000DJX70 19 B00020LXYA 36.51714 50.07857 
7 428 B0000DJX70 20 B00020LXYA 36.22286 37.67000 
8 429 B0000DJX70 21 B00020LXYA 36.31714 37.67000 
9 430 B0000DJX70 22 B00020LXYA 36.39286 38.14286 

然後,在翻譯時獲取到,如果塊和快進去吧,它無法返回NA,並出現以下奇怪的錯誤:

Error in if (xor(((max(x, na.rm = TRUE) - mean(x, na.rm = TRUE)) < (mean(x, : 
    missing value where TRUE/FALSE needed 
In addition: Warning messages: 
1: In max(x, na.rm = TRUE) : 
    no non-missing arguments to max; returning -Inf 
2: In min(x, na.rm = TRUE) : 
    no non-missing arguments to min; returning Inf 

雖然警告是:

Warning messages: 
1: In max(x, na.rm = TRUE) : no non-missing arguments to max; returning -Inf 
2: In min(x, na.rm = TRUE) : no non-missing arguments to min; returning Inf 

我無言以對,因爲這個函數被調用在一個循環,並能正常工作了很多次,僅與此特定的數據集失敗。 任何幫助提前感謝

另外:

Browse[2]> dput(unique(data$bundles_product_id)) 
"B0000DJX70" 
+2

我猜測,'唯一的(數據$ bundles_product_id)== 'B0000DJX70' '返回一個向量,'if'沒有向量化。可能會把它包裝成任何東西,儘管它不是很清楚你想達到什麼目的。 –

+0

根據您收到的信息判斷,問題不在所提供的「if」語句中。 –

+0

大衛 - 我加了關於YOUT句話的東西,好像是唯一的(數據$ bundles_product_id)不返回矢量 – Nirke

回答

0

對我來說是預期的行爲:

dat <- read.table(text = "1 422 B0000DJX70 14 B00020LXYA 32.33071 55.93000 
2 423 B0000DJX70 15 B00020LXYA 32.10714 53.74429 
3 424 B0000DJX70 16 B00020LXYA 30.45429 53.08143 
4 425 B0000DJX70 17 B00020LXYA 31.82214 50.21000 
5 426 B0000DJX70 18 B00020LXYA 33.01727 49.98429 
6 427 B0000DJX70 19 B00020LXYA 36.51714 50.07857 
7 428 B0000DJX70 20 B00020LXYA 36.22286 37.67000 
8 429 B0000DJX70 21 B00020LXYA 36.31714 37.67000 
9 430 B0000DJX70 22 B00020LXYA 36.39286 38.14286", header=F,stringsAsFactors =FALSE) 

pa <- function(data){ 

    if (unique(data$V3) == 'B0000DJX70'){ 
    print ('B0000DJX70') 
    return(NA) #invisible() would be better 
    }} 
pa(dat) 
[1] "B0000DJX70" 
[1] NA