mercredi 23 mai 2018

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

I have two vectors that can be of variable length. I want to constrain how I sample from one by using the length of the smaller one. In this case, xy is smaller so the first part should execute and the second should be ignored, but when I run the code I get an error:

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)
  }

The error makes sense on its own, if I run those lines with sample separately but I thought the if else coding should prevent that.




Aucun commentaire:

Enregistrer un commentaire