Announcement

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

  • Creating a forvalue with several i (or; Generating a new variable with forvalue)

    Dear all,

    I'm trying to create several variables, called Pv1, PV2, PV3, PV4, PV5. I could explain all the details in a comment later, but I think it will be too much if I'd put all the background info in this post.

    For each variable, I need to put several conditions. I guess the quickest way to create PV1 is:

    Code:
    gen pv1=MAT1 if IDSUBJ==1
    replace pv1=SCI1 if IDSUBJ==2
    replace pv1=REA1 if IDSUBJ==4
    replace pv1=(MAT1+SCI1)/2 if IDSUBJ==3
    replace pv1=(MAT1+SCI1)/2 if IDSUBJ==6
    replace pv1=(SCI1+REA1)/2 if IDSUBJ==7
    I'd of course like to do the above in a quicker way if possible, but my main question is the following:
    I'd like to create a forvalue so that the above is looped, with i going from 1 to 5. So:

    Code:
    forvalues i = 1(1)5 {
    gen pvi=MATi if IDSUBJ==1
    replace pv1=SCIi if IDSUBJ==2
    ...etc
    But when i run it, it doesn't recognize 'MATi' as MAT1 for the first iteration. I guess it's either because there is already an i in pvi, or because the i can't be inside of a variable name. How can I make it recognize this, or get around it?

    Many thanks,
    Ahmad



  • #2
    To make it clear for Stata that you are referring to i from your forvalues numlist and not string "i", you need to wrap i in quotes:
    Code:
    `i'

    Comment


    • #3
      Cross-posted at https://www.reddit.com/r/stata/comme...or_generating/

      Please note our cross-posting policy, which is that you should tell us about it. The folks at Reddit might appreciate a cross-reference too.

      Comment


      • #4
        Thank you both, for the help and the note about cross-posting etiquette. Edited the reddit post.

        Comment

        Working...
        X