Announcement

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

  • Loop for overlaying mulple kdensity plots.

    Dear all,

    I have a overlaying kdensity plot of which the codes are given below. Is there anyway to make it through a loop instead typing the command line for each "visit". I need to make 16 for each gender, therefore, a loop will be very useful and efficient approach.

    Many thanks in advance for your help.

    Code:
    twoway (kdensity y if visit==5 & gender==1) || ///
           (kdensity y if visit==6 & gender==1) || ///
           (kdensity y if visit==7 & gender==1)
    Best,
    Roman

  • #2
    twoway kdensity does support a by() option. 16 different panels might be a lot easier than a mess of 16 superimposed curves.Also, with 16 curves the legend takes up a lot of real estate. But yes, you can loop.

    Code:
     
    forval j = 1/16 { 
         local call `call' (kdensity y if visit==`j' & gender == 1) || 
    } 
    twoway `call'

    Comment


    • #3
      Thank you so much Nick. 'by' option certainly more elegant and I have decided to use that but as a bonus to this post, I have learned another variant of looping. Fantastic.
      Roman

      Comment


      • #4
        By the way, could it be done with specific values of `j' i.e.

        Code:
        forval j = 1 5 10 16 {
             local call `call' (kdensity y if visit==`j' & gender == 1) ||
        }
        twoway `call'
        I get ''invalid syntax'' warning when I try doing that.
        Roman

        Comment


        • #5
          The -forvalues- construct has a very restricted syntax and does not accommodate arbitrary number lists. To do what you want requires a -foreach- loop:

          Code:
          foreach j of numlist 1 5 10 16 {
              whatever
          }

          Comment


          • #6
            Clyde is naturally quite correct. The underlying logic is that if you give a rule to forvalues for looping over integers then it doesn't need to evaluate and store a sequence beforehand. That makes forvalues faster. It's true that everything you can do with forvalues, you can do in foreach, but not vice versa.

            Comment


            • #7
              This is such a luxury. Many thanks Clyde, worked perfect.
              Roman

              Comment


              • #8
                Thanks Nick. Very sensible explanation and I can clearly see the logic behind the two programs.
                Roman

                Comment

                Working...
                X