adkane
adkane

Reputation: 1441

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.

Upvotes: 1

Views: 69

Answers (2)

moooh
moooh

Reputation: 469

In your if statement you need to use the lengths rather than the raw vectors:

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

Upvotes: 1

Alok VS
Alok VS

Reputation: 186

Just change the if condition to,

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

Upvotes: 1

Related Questions