Announcement

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

  • Repetitive but simple programming using foreach

    I wrote a program for repetitive but simple work using foreach. But it didn't work.

    For a variable of fc1, I recoded the variable, creating a new variable of r_fc1 as belows:
    recode fc1 (1=100)(2=75)(3=50)(4=25)(5=0), gen(r_fc1)

    But I wanted to make it simple because I should do that for fc2...fc5. So I wrote as belows:
    foreach N of numlist 2/5 {

    recode fc'N' (1=100)(2=75)(3=50)(4=25)(5=0), gen(r_fc'N')
    }

    But it resulted in the following:
    fc ambiguous abbreviation
    r(111);


    What is wrong with it?
    I would like to do the same thing to the variables of comp1...comp4, coord1...coord3.
    Can you give some advices on a right, smarter programming?
    Last edited by Yong-jun Choi; 03 Sep 2016, 20:59. Reason: I added tags to the posting.

  • #2
    The problem is with
    Code:
    recode fc'N' (1=100)(2=75)(3=50)(4=25)(5=0), gen(r_fc'N')
    You are using the wrong quote characters to refer to the local macro N. Correct is:
    Code:
    recode fc`N' (1=100)(2=75)(3=50)(4=25)(5=0), gen(r_fc`N')
    Look carefully at the quotes surrounding each reference to N. The correct left quote is not a vertical quote, it slopes down from left to right (`). On an American keyboard, it is found on the key immediately to the left of the 1! key. The right quote, which you have correct in your original, is the ordinary vertical quote (').

    Added: I tried to draw visual attention to it by putting that character in red, but it doesn't really stand out all that well. Bold face isn't noticeable either. Sorry.

    Comment


    • #3
      Dear Professor Clyde Schechter:

      Thank you for your advice. Small things make a difference.

      Yong-jun Choi

      Comment


      • #4
        Not a problem here but looking at the help for forvalues and foreach shows that

        Code:
        foreach N of numlist 2/5
        is equivalent to

        Code:
        forval N = 2/5
        and there is no gain whatever in the first form except as a way of practising syntax.

        Comment


        • #5
          Thank you, professor Cox. You make it clear to me.

          Comment

          Working...
          X