Is there is a way in R language to write a fast IF like in C++:
if (a==b)
return 1
else
return 0
// Fast way
(a==b ? 1 : 0)
Join Stack Overflow to learn, share knowledge, and build your career.
Is there is a way in R language to write a fast IF like in C++:
if (a==b)
return 1
else
return 0
// Fast way
(a==b ? 1 : 0)
Well actually R's ifelse()
function already sort of encapsulates the same behavior as a C-style ternary expression:
ifelse(a == b, 1, 0)
Note that ifelse
is already vectorized, meaning that the inputs a
and b
can be vectors, and it will still work.
ifelse
works. Each pair of values at every index of a
and b
get compared, and a single scalar value is the output, not a vector output.
– Tim Biegeleisen
Nov 22 '20 at 4:01
You can convert the logical values returned from ==
to integer in R. So this should work.
as.integer(a == b)
For example,
a <- c(2, 4, 5, 6)
b <- c(3, 4, 7, 6)
as.integer(a==b)
#[1] 0 1 0 1
+(a == b)
– rawr Nov 22 '20 at 7:29