Announcement

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

  • Counting number of variables in a data set and generating dummy variables to pad out total number of variables

    Hi all,

    I'm using Stata 14.1. I have a number of data sets that I am trying to apply universal formatting to. Some data sets have 10 variables and some have say 8 or 9. What I want to do is insert a dummy variable (that can be blank) in order to bring the total number of variables up to 10 so that I can use a consistent formatting script across all data sets. I may have 20 data sets, so don't wish to open and close each data set. Is anyone aware of a way I can count the number of variables in the current data set and generate an extra variable if the total number is fewer than a set number?

    Thanks

    Tim

  • #2
    As a follow-up, I think this is what I need:

    Code:
    sysuse auto, replace
    describe
    di r(k)
    if `r(k)' <14 {
    generate dummy = ""
    }
    else if `r(k)'=>13 {
    di `r(k)'
    }

    Comment


    • #3
      Code:
      //    DETERMINE NUMBER OF VARIABLES AND EXPAND TO 20
      
      local vars_needed 10
      
      use my_data, clear
      des, short
      local n_vars `r(k)'
      
      forvalues j = `=`n_vars'+1'/`vars_needed' {
          gen placeholder`j' = .
      }
      Note: this code creates numeric placeholder variables with all missing values. If you need strings, just change it to -gen placeholder`j' = ""-.

      Added: Crossed with #2. The solution there will work if the data set either has the desired number of needed variables, or is exactly one short. The solution here will work regardless of how many variables need to be created to reach the desired count. In any case, Tim's solution seizes on the key point that -des- returns the number of variables in r(k).
      Last edited by Clyde Schechter; 12 Sep 2017, 08:48.

      Comment


      • #4
        Thanks Clyde Schechter my solution only works if you know that the there is only one potential 'missing' variable - your version answers my original question more precisely.

        Comment

        Working...
        X