为什么我的 if else 语句在与 R 中的示例函数结合时会失败

Why does my if else statement fail when combined with the sample function in R

我有两个可变长度的向量。我想通过使用较小的一个的长度来限制我从一个采样的方式。在这种情况下,xy 较小,因此第一部分应该执行,第二部分应该被忽略,但是当我 运行 代码时,我得到一个错误:

Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE' In addition: Warning message: In if (xx > xy) { : the condition has length > 1 and only the first element will be used

  xy<-c(1:5)
  xx<-c(1:10)

  if(xx > xy){
    father<-xy;
    mother<-sample(xx,length(xy), replace = FALSE)
  } else {
    mother<-xx;
    father<-sample(xy,length(xx), replace = FALSE)
  }

错误本身是有道理的,如果我 运行 那些带有 sample 的行,但我认为 if else 编码应该可以防止这种情况发生。

把if条件改成,

 if(length(xx) > length(xy))

在您的 if 语句中,您需要使用长度而不是原始向量:

if(length(xx) > length(xy)) {...}