x <- seq(0.1,10,0.1)
y <- if (x < 5) 1 else 2
I would want the if
to operate on every single case instead of operating on the whole vector.
What do I have to change?
x <- seq(0.1,10,0.1)
y <- if (x < 5) 1 else 2
I would want the if
to operate on every single case instead of operating on the whole vector.
What do I have to change?
For completeness: In big vectors, you can use the indices to speed things up (we do that often in simulations, where functions typically run 1000 to 10000 times). But as long as it isn't necessary, just use
ifelse
. This reads a lot easier.y <- if (x < 5) 1 else 2
does not operate on the whole vector (the warning you receive tells you only the first element of the condition will be used). You wantifelse
:ifelse
operates on the whole logical vector, element-by-element.if
only accepts one logical value. See?"if"
and?ifelse
Following the above post you can even use and modify the elements of a vector satisfying the criteria. In my opinion if it's not more costly to compute faster one should always do it.
The code of the previous post is best to answer the question. But if I had to use the code above I would do:
You could also just create a logical vector and 1 to it
If would like to compare performance, it would be the fastest solution