Announcement

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

  • every sequence of rows replace for a certain value

    Hi everyone,

    I generated a variable (gen perc=.) and would like to give it a certain value every few rows. Like the below:
    perc
    p10
    p50
    p90
    p10
    p50
    p90
    p10
    p50
    p90
    I believe I have to do a loop, but couldn't find any similar example in the forum. Could you please help me with the code?

    Thank you,

  • #2
    No need for a loop:
    Code:
    gen perc = "p10" if mod(_n, 3) == 1
    replace perc = "p50" if mod(_n, 3) == 2
    replace perc = "p90" if mod(_n, 3) == 0

    Comment


    • #3
      Obfuscated code competition

      Code:
      gen perc = cond(mod(_n, 3) == 1, "p10", cond(mod(_n, 3) == 2, "p50", "p90"))

      Comment


      • #4
        Mathiest code competition.
        Code:
        gen perc = word("p90 p10 p50",1+mod(_n,3))
        Added in edit: Now with addition and multiplication!
        Code:
        gen perc = "p"+string(10+40*mod(_n+2,3))
        Where is Romalpa Akzo whose creatively elegant solutions are needed here?
        Last edited by William Lisowski; 02 Feb 2022, 19:11.

        Comment


        • #5
          Thanks, William Lisowski​​​​​ for your encouragement. Your first solution in #3 is my favourite. No solution could be more concise, I guess. The below code is just for fun, which shows that string could also be multiplicable in Stata.

          Code:
          gen perc3 = !mod(_n,3)*"p90" + !mod(_n+1,3)*"p50" + !mod(_n+2,3)*"p10"
          Last edited by Romalpa Akzo; 02 Feb 2022, 19:49.

          Comment


          • #6
            Thank you, that is amazingly novel. As usual, you see these problems from a perspective uniquely your own.

            Comment

            Working...
            X