Announcement

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

  • Generate a variable with string of column names meeting criteria

    Hello
    I would like to generate a variable that is a string combination of variable names meeting a specified criteria. In this example, I would like to generate a variable, called "treatment" equal to the combination of a list of variable names where the value is "1" for the variable(s). For example for the first row, "treatment" would equal "ind_cytotoxic_therapy, ind_alkylating_agent". For the second row "treatment" would be "ind_cytotoxic_therapy, ind_targeted_therapy, ind_alkylating_agent". In my real dataset I have thousands of variables and there are 50 variables that I would like to apply this to.
    Any help would be greatly appreciated!!

    Many Thanks,
    Kelly Bolton
    MSKCC

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str2(ind_biologic_therapy ind_cytotoxic_therapy ind_hormonal_therapy ind_immune_therapy ind_radiotherapy ind_targeted_therapy ind_alkylating_agent)
    "0" "1" "0" "0" "0" "0" "1"
    "0" "1" "0" "0" "0" "1" "1"
    "0" "1" "1" "0" "0" "0" "1"
    "0" "1" "0" "0" "0" "0" "1"
    "0" "1" "0" "0" "0" "1" "1"
    end

  • #2
    Code:
    gen Wanted = ""
    
    foreach v of var * {
        replace Wanted = cond(Wanted =="", "`v'", Wanted + "," + " `v'") if `v' == "1"
    }

    Comment


    • #3
      Code:
      gen wanted = ""
      foreach v of varlist ind_biologic_therapy-ind_alkylating_agent {
          replace wanted = wanted + (cond(`v' == "1", " `v'", ""))
      }
      replace wanted = trim(wanted)
      I am curious why these ind_* variables are being stored as strings. I don't know what you plan to do with them, but for most purposes, it will make your life easier if you -destring- them and work with them as numeric 0/1 variables.

      Added: Crossed with #2, which gives a comma-separated list instead of a space separated list.

      Comment

      Working...
      X