Announcement

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

  • Generating mulitple local variables from multiple values of a single variable

    Hi all,

    I am new to STATA, and I am trying to pick up new coding to improve my efficiency. The subject line says it all for what I am trying to accomplish.

    The example: I have a variable that is a classification system "ota_classification" for which there are 9 coded values (1,2,3...9). What I would like to do is generate a local variable (without actually keeping the variable) for each of the values so that I can run a chi-square against each different value for the classification system.

    I can do this the long way ie.

    gen ota_classification1 = ota_classification =1
    tab ota_classification1 outcome, chi row
    gen ota_classification2 = ota_classification =2
    tab ota_classification2 outcome, chi row
    etc etc

    Can I do this with the foreach or forvalues command along with "local" so that I am not truly generating a new variable every time?

    Thanks in advance for the help.

  • #2
    Since you don't provide example data of your own to work with, here is an illustration using the built-in auto.dta set to show you how it is done:

    Code:
    sysuse auto, clear
    
    levelsof rep78, local(rep78s)
    gen byte stratum = .
    foreach r of local rep78s {
        replace stratum = `r'.rep78
        label var stratum "rep78 == `r'"
        tab stratum foreign, chi2 row
    }
    In the future, when you want help with code, show an example of your own data. The solution often depends on details of the data that are difficult or impossible to describe in words. (For example, my code above will only work with a numeric variable rep78; it can be modified for strings, but will not work as is.) So use the -dataex- command to show example data. If you are running version 15.1 or a fully updated version 14.2, it is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Comment

    Working...
    X