Question

I often want to tabulate the product of two variables. For example, suppose that I have x1 and x2, both of which are integer-valued. In R, table(x1 * x2) does what I want. I don't need to create a new variable (say, x3) to get the information that I need.

I want to do the same in Stata. That is, I want to run a command like tabulate x1*x2. (I need to do this sort of thing all the time, which is one reason why I don't first want to create a new variable x3.) Is there a way to do this in Stata?

Was it helpful?

Solution

I don't think you can get this kind of behavior without some programming effort. Notice that tabulate requires varnames or varlists, and expressions are not allowed. See help tabulate. Naturally, generate is a command that does allow expressions. See help exp for some details.

I recall a discussion along the lines of "on-the-fly computations" in Statalist but I'm not able to find it right now; you might want to check the archives. If I recall correctly, this was not possible for things other than factor variables which you can use "on-the-fly" with factor variable notation (help factor variables). I remember there were good reasons for why this is the case.

But for something like the product of two variables you could write a simple program in an .ado file, save it in a Stata system directory (preferably ~/ado/personal/) and then use it whenever you like.

Here is an example program:

program define tabulate2, byable(recall)

    /* 
    Tabulate the product of two variables.
    Modeled after the official -tab1- command.
    */

    version 12
    syntax varlist(min=2 max=2 numeric) [if] [in] [, *]

    tokenize `varlist'

    tempvar prod
    gen `prod' = `1' * `2'
    label var `prod' "`1' x `2'"

    tempvar touse
    mark `touse' `if' `in'

    capture noisily tabulate `prod' if `touse', `options'

end

And some code that makes use of the newly defined command tabulate2:

clear all
set more off

input ///
var1 var2
1 2
3 4
3 4
3 4
5 6
end

list

tabulate2 var1 var2

The output:

. tabulate2 var1 var2

var1 x var2 |      Freq.     Percent        Cum.
------------+-----------------------------------
          2 |          1       20.00       20.00
         12 |          3       60.00       80.00
         30 |          1       20.00      100.00
------------+-----------------------------------
      Total |          5      100.00

Not perfect, but I hope you get the idea.

See also help program and references therein.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top