Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to define a function or program and cite it to generate a new variable?

    What I want to do is to generate a new variable y following some self-defined function f() and existing variable x. For example, f(x)=x^2.

    My question is how to define a program or a function that has argument x and would output a new variable y when I cite it using gen y=f(x) or f x?

    I know this example can be done simply by gen y=x^2, but I need to use this structure to do some further programming. Thanks for your help!

  • #2
    Can anyone give me some hint?

    Comment


    • #3
      You cannot define functions in Stata, but the egen suite of commands emulates the syntax of functions. So, you might take a look at its ado file and the ones that it calls for hints for how to go about writing your own.

      An alternative is to work in Mata, which does allow user-defined functions, but requires a bit more effort to work with Stata's dataset.

      Comment


      • #4
        egen is fine, if you want your function to be available outside your program. If I do that within my own program I will typically create a small local program, something like so:

        Code:
        *! version 1.0.0 20Feb2017 MLB
        program define main_prog
            ...
            temvar newvar
            sub_prog `x', gen(`newvar')
            ...
        end
        
        program define sub_prog
            syntax varname(numeric), GENerate(name)
            generate double `generate' = `varlist'^2
        end
        Depending on the circumstances, predict functions may also be appropriate.
        ---------------------------------
        Maarten L. Buis
        University of Konstanz
        Department of history and sociology
        box 40
        78457 Konstanz
        Germany
        http://www.maartenbuis.nl
        ---------------------------------

        Comment


        • #5
          Thanks for the answers!

          Comment

          Working...
          X