6

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}

Any better way please?

ramesh
  • 2,309
  • 16
  • 29

4 Answers4

5
Boole@Thread[Greater[x, y]] ==  MapThread[Boole@Greater@## &, {x, y}]
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
2
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] &;
f7 = Boole@Thread[Greater[##]] &;
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]

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896
1

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]]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Thank you Mr. Wizard. I would appreciate it if you would also look at my other question: https://mathematica.stackexchange.com/questions/152405/datelistplot-of-multiple-time-series-with-data-values-and-legend-appearing-as-th – ramesh Jul 30 '17 at 20:46
1
Boole[#1 > #2 & @@@ Transpose[{x, y}]]

Or

Transpose[{x, y}] /. {x_, y_} :> Boole[x > y]
Karsten7
  • 27,448
  • 5
  • 73
  • 134