2015-07-12 123 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