Announcement

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

  • generate variable indicating variable name where observation is not missing

    Hello,
    in my dataset i have several variables which either have the value of 1 or are missing. For every row there is only one variable where the value is 1 and not missing.
    I want to create a new variable now, that indicates the variable name of the variable that is NOT missing.

    this is an example of my data:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(Firm94 Firm121 Firm133 Firm241 Firm246 Firm301 Firm478 Firm499 Firm522 Firm590 Firm731 Firm742 Firm1310 Firm1672 Firm1843 Firm1910)
    1 . . . . . . . . . . . . . . .
    1 . . . . . . . . . . . . . . .
    1 . . . . . . . . . . . . . . .
    . 1 . . . . . . 1 . . . . . . .
    1 . . . . . . . . . . . . . . .
    1 . . . . . . . . . . . . . . .
    . . . . 1 . . . . . . . . . . .
    1 . . . . . . . . . . . . . . .
    1 . . . . . . . . . . . . . . .
    1 . . . . . . . . . . . . . . .
    end

    now i would like to have a variable, for example called "Firm", as a string that writes Firm94 in first, second, third row, Firm121 in fourth row and so on.
    At first i thought this should be pretty straight forward but i somehow cannot wrap my head around it.
    Can someone help me with this ?
    thank you in advance !



  • #2
    What about something like this?

    Code:
    gen newvar = .
    foreach num in 94 121 133 241 246 301 478 499 522 590 731 42 1310 1672 1843 1910{
        replace newvar = Firm`num' if Firm`num' == 1
    }
    I haven't tested this since I am not at a computer with Stata installed, but I think it should work.

    Comment


    • #3
      Actually, just thinking about it, you might need to surround the first Firm`num' in quotes to make sure it is interpreted as a string.

      Code:
      replace newvar = "Firm`num'" if Firm`num' == 1

      Comment


      • #4
        Code:
        gen wanted=""
        foreach var of varlist Firm*{
            replace wanted= "`var'" if missing(wanted) & `var'==1
        }
        Last edited by Andrew Musau; 28 May 2022, 15:26.

        Comment


        • #5
          Andrew, that worked perfectly. thank you !

          Comment

          Working...
          X