Announcement

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

  • Stack variables by another variable

    Hello,

    I previously posted a thread about stacking variables. See here: https://www.statalist.org/forums/for...ange-of-values

    I cannot post the data, so I use the example of people being surveyed on their two favorite foods. The data looks like this:

    Code:
    ID fav1 fav2 gender
    1 pizza burger 0
    2 burger pizza 1
    3 steak burger 1
    4 burger steak 0
    The fav1 and fav2 variables would be stacked into one variable this way:

    Code:
    stack fav1 fav2, into(fav)
    A bar graph of this would be created:

    Code:
    graph bar (count), over(fav)
    In addition to a normal bar graph, I would like to do separate bar graphs by gender. Is there a way to preserve the gender variable through the stack, in order to later create two separate bar graphs by gender?
    Last edited by Greg Saldutte; 02 Oct 2019, 11:34.

  • #2
    Your previous thread was here https://www.statalist.org/forums/for...ange-of-values ; please give a cross-reference so that people can find it easily.

    Similarly, in that thread I re-engineered your data example as input code and doing that is a good idea.

    What you want is a small extension of the previous answer


    Code:
    clear 
    input ID str6(fav1 fav2) gender 
    1 pizza burger 1
    2 burger pizza 0 
    3 steak burger 0 
    4 burger steak 1
    end 
    
    stack fav1 gender fav2 gender, into(fav gender)  
    graph bar (count), over(fav) over(gender)
    The help for stack does give examples of repeating variables in this way.

    Comment


    • #3
      I'm wondering why not just use the if qualifier for separate graphs, or addding - over(sex) - for a separate display on the same graph.

      P.S.: Crossed with Nick's insightful reply. My suggestion was exactly his second line code.
      Best regards,

      Marcos

      Comment


      • #4
        Thank you both. The problem is now solved.

        Comment

        Working...
        X