Announcement

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

  • Generating New Variable Based on Minimum Value

    Hi all,

    I'm having trouble generating variables based on a certain condition. Below is a simple example. I'm trying to generate a variable that will be filled with a school name (in this case, either Brown or Gordon) if that school has the lowest corresponding distance in the column. For example, If I were to create a new variable (say, SchoolMatch01) based on Distance01, it would fill out with "Brown." Another variable based on Distance02 would be filled with "Gordon." Is there any easy way to code for this? I've tried using macro commands but I can't figure out how to get some sort of minimization function in there. Please let me know if there is any difficulty understanding the question. It is somewhat hard to explain.

    Thanks,

    Thomas


    ID School Distance01 Distance02
    1 Brown 4 9
    2 Gordon 7 2
    3 Reno 9 4

  • #2
    Here is the general direction I've been going with this problem:
    Code:
    forvalues id = 01/02 {
    generate SchoolMatch`id' = School[_n] if (Distance`id'[_n] = min(Distance`id'))
    }

    Comment


    • #3
      Here is a simple approach. Note that including ID in the sort insures that the same result (the smallest distance with the lowest ID) will always be given.
      Code:
      clear
      input ID str8 School Distance01 Distance02
      1 Brown  4 9
      2 Gordon 7 2
      3 Reno   9 4
      4 Gnxl   4 2
      end
      foreach dnum in 01 02 {
      sort Distance`dnum' ID
      generate SchoolMatch`dnum' = School[1]
      }
      sort ID
      list, noobs abbreviate(16)
      Code:
        +-----------------------------------------------------------------------+
        | ID   School   Distance01   Distance02   SchoolMatch01   SchoolMatch02 |
        |-----------------------------------------------------------------------|
        |  1    Brown            4            9           Brown          Gordon |
        |  2   Gordon            7            2           Brown          Gordon |
        |  3     Reno            9            4           Brown          Gordon |
        |  4     Gnxl            4            2           Brown          Gordon |
        +-----------------------------------------------------------------------+

      Comment


      • #4
        Thanks William. This should do the trick. I've quoted you in the general section where I made the same post so that others can see your solution.

        Comment

        Working...
        X