简体   繁体   English

从R函数返回值

[英]Returning a value from R function

I have the following R function 我有以下R功能

pa <- function(data){

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

} data looks like this: }数据如下所示:

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

Then, when the interpreter gets to the if block and get inside it, it fails returning NA with the following strange error: 然后,当解释器到达if块并进入其中时,它无法返回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

while the warnings are: 警告是:

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

I'm clueless, since this function is called in a loop and works fine many times, only with this specific data set it fails. 我一无所知,因为此函数是在循环中调用的,并且可以正常工作很多次,只有在使用此特定数据集的情况下,它才会失败。 Any help appreciated in advance 提前感谢任何帮助

addition: 加成:

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

To me the behavior is as expected: 对我来说,行为符合预期:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM