# Easiest way to create a binary variable

Binary variable is often used in applied statistics. However, I had a hard time to figure out how to create it. Somebody might have better idea how to do it. I have two variables say x and y as follows

x = Range[100];
y = Flatten[RandomInteger[{1, 100}, {100, 1}]];


I want to create a binary variable b1 such that b1 = 1 if x>y and 0 otherwise. I have done so far

b1 = TrueQ[#1 > #2] & @@@ Transpose[{x, y}] /. {True -> 1, False -> 0}


Boole@Thread[Greater[x, y]] ==  MapThread[Boole@Greater@## &, {x, y}]

• Thank you belisarius for your answer. Commented Feb 10, 2015 at 16:02
• Or just Boole@Thread[x > y]. Commented Feb 10, 2015 at 16:02
Inner[Greater, x, y, Boole @ {##} &]
Inner[Boole@Greater@## &, x, y, List]
Inner[Composition[Boole, Greater], x, y, List]
Boole @ Inner[Greater, x, y, List]


Update: Timings

ClearAll[r1, r2, r3, r4, r5, r6, r7, r8, r9, r10,
t1, t2, t3, t4, t5, t6, t7,  t8, t9, t10,
f1, f2, f3, f4, f5, f6, f7,  f8, f9, f10, functions, results, timings]
f1 = Inner[Greater, ##, Boole@{##} &] &;
f2 = Inner[Boole@Greater@## &, ##, List] &;
f3 = Inner[Composition[Boole, Greater], ##, List] &;
f4 = Boole@Inner[Greater, ##, List] &;
f5 = Boole[#1 > #2 & @@@ Transpose[{##}]] &;
f6 = Transpose[{##}] /. {x_, y_} :> Boole[x > y] &;
f8 = MapThread[Boole@Greater@## &, {##}] &;
f9 = 1 - UnitStep[#2 - #] &;
f10[x_, y_] := Subtract[1, UnitStep@Subtract[y, x]];

functions = {"f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10"};
results = {r1, r2, r3, r4, r5, r6, r7, r8,r9, r10};
timings = {t1, t2, t3, t4, t5, t6, t7, t8, t9, t10};

SeedRandom[1]
x = Range[1000000];
y = Flatten[RandomInteger[{1, 100}, {1000000, 1}]];
(# = First[AbsoluteTiming[(#2 = ToExpression[#3][x, y]);]]) & @@@
Transpose[{timings, results, functions}];

Equal @@ results


True

Grid[Prepend[SortBy[Transpose[{functions, ToExpression /@ functions, timings}],
Last], {"name", "function", "timing"}], Dividers -> All]


• kguler, thank you for your answer. Commented Feb 10, 2015 at 16:03
• Would you kindly add my code to your timings, unless I made a mistake or misunderstood? (In which case I'll delete.) Commented Jul 29, 2017 at 17:42
• @Mr.Wizard, done ...
– kglr
Commented Jul 29, 2017 at 17:58
Boole[#1 > #2 & @@@ Transpose[{x, y}]]


Or

Transpose[{x, y}] /. {x_, y_} :> Boole[x > y]


Maybe I'm missing something but I think I would just use UnitStep:

1 - UnitStep[y - x]


This will be a little faster with explicit Subtract due to (40927):

Subtract[1, UnitStep @ Subtract[y, x]]