I am running a short if function in R but am getting the following warning message:
In if ((runif(50, 0, 1) < 0.69)) { : the condition has length > 1 and only the first element will be used`.
My rudimentary grasp of R leads me to believe that runif generates a vector but if yields a single value, so I’m thinking this is the issue. Is there any simple substitution for if here?
Also i want the end product to be a matrix combination of the two arguments but i wasn’t sure if it was correct to put 50 in the rnorm function for both scenarios.
Test <-
if((runif(50, 0, 1)<0.69)) {
rnorm(50, 25, 4)
} else {
rnorm(50, 28, 4.3)
}
if()expects whetever is in the parentheses to evaluate to a logical vector of length 1 (TRUEorFALSE). If the vector is longer than 1, then as the warning says only the first element of the vector is used.An alternative if
ifelse()where it is used as :For your example we have:
or
Either is OK as
ifelse()generates the two vectors forTRUE_CASEandFALSE_CASEbefore doing the comparisons.Example output is:
Another way is to do this is to only generate the required values
That obviously gives different numbers to the previous ones but only because we generated fewer random numbers. I doubt this will be any more efficient than
ifelse()for most problems.