【问题标题】:Why does my if else statement fail when combined with the sample function in R为什么我的 if else 语句与 R 中的示例函数结合使用时会失败
【发布时间】:2018-05-23 10:01:43
【问题描述】:

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

sample.int(length(x), size, replace, prob) 中的错误:不能取 'replace = FALSE' 时样本大于总体另外: 警告消息:在 if (xx > xy) { :条件长度 > 1 并且只使用第一个元素

  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(xx &gt; xy)你可以使用if(length(xx) &gt; length(xy))

标签: r if-statement random conditional


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    只需将 if 条件更改为,

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

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2020-09-06
      • 2018-07-30
      • 2020-11-04
      • 2018-12-03
      • 1970-01-01
      • 2021-03-04
      • 2012-09-28
      • 2021-11-14
      相关资源
      最近更新 更多