0

I want to create two vectors in R that contain values randomly drawn from a uniform distribution given a specified condition, that is for example if the number in vector A is < 50 then the number in vector B should be greater than 50.

I use this code but it is applied only on the first element of the vectors

nrows = 20
A = NaN*matrix(1, nrows, 1)
B = NaN*matrix(1, nrows, 1)

repeat {
  A[] = round(runif(nrows, 10, 100), digits =2) 
  B[] = round(runif(nrows, 10, 100), digits =2) 
  if(A > 50 & B > 50) {
    break
  }
}
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • 2
    Two methods: `A <- runif(10, 0, 100)` then `B <- 100 - A`. Or same A, then `B <- runif(10, 0, 50) + ((A < 50) * 50)`. – lmo Oct 03 '17 at 11:59
  • thank you very much for the reply. Maybe my question wasnt explanatory enough, lets assume that A =12.03 then B should be in [50.00,100] or vice versa. teh sum of A and B can be different that 100 – user4129939 Oct 03 '17 at 12:06
  • 2
    My second suggestion works in that situation. – lmo Oct 03 '17 at 12:18

1 Answers1

0

This should work for you if i understood the problem correctly:

nrows = 20
A = NaN * matrix(1, nrows, 1)
B = NaN * matrix(1, nrows, 1)

for (i in 1:nrows) {
  A[i] <- round(runif(1, 10, 100), digits = 2)
  if (A[i] < 50) {
    B[i] <- round(runif(1, 50, 100), digits = 2)
  } else {
    B[i] <- round(runif(1, 10, 100), digits = 2)
  }
}
f.lechleitner
  • 3,554
  • 1
  • 17
  • 35