How to Compute Binary Variables Using JavaScript

From Q
Jump to navigation Jump to search

Binary variables can be created using JavaScript (see JavaScript Variables for an introduction to creating variables using JavaScript).

Simple syntax

The following code computes a value of 1 if the observation has a value of 1 for any of the three input variables:

if (d1 == 1 || d2 == 1 || d3 == 1) 1;
else 0

whereas this code computes a value of 1 if the observation has given a value of 1 for all of the input variables:

if (d1 == 1 && d2 == 1 && d3 == 1) 1;
else 0

See JavaScript Tips if you are surprised by the use of ==, || and && or are unclear how this may relate to more complicated examples.

Shorter syntax

People new to JavaScript are a little surprised by these expressions, as they often think it would be better if the symbols were not repeated (e.g., writing d1 = 1 & d2 = 1 instead of d1 == 1 && d2 == 1). There are good-but-technical reasons why JavaScript does not work this way (e.g., = is used to create variables: see Writing ‘Real’ Code). However, there are a number of ways to make the code much shorter if that is desired. There is no need for an if statement as any logical expression in JavaScript is automatically evaluated as a 1 or 0, and thus we can write:

d1 == 1 && d2 == 1 && d3 == 1

and, if we know that the input variables are themselves binary, only taking values of 1 and 0 (and with no missing values), we could just write:

d1 && d2  && d3

or

d1 * d2  * d3

Automation

If there is a need to create many related binary variables using JavaScript, this can be done using either QScript or Use as Template for Replication.

See Also