从R函数返回一个值

时间:2015-07-12 13:17:29

标签: r function return

我有以下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

然后,当解释器到达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

虽然警告是:

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"

1 个答案:

答案 0 :(得分: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