Announcement

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

  • Generating values in a variable through two other variables in the dataset

    Hi!
    I need help to create the values in a variable automatically from two other variables.

    My data consists of a number of distance variables called dist_1, dist_2, dist_3 and etc which is a code for the individuals postalcode, it also consists of a variable called skolepostnr, which indicates which postalcode the school an individual attends to and postnummer, which indicates the postalcode an individual lives in. I have created a variable called dist_skole_hjem, which should be used to measure the distance between an individuals home and school, fx the individual have skolepostnr=3 and postnummer=2, so the dist_skole_hjem in this case should equal 55.


    Postnummer dist_1 dist_2 dist_3 ... skolepostnr dist_skole_hjem
    1 20,5 40,7 90 1
    2 45 120 55 3
    ... ... ... ... ...
    Since there are a lot of observations in my dataset, I would like to know if there is some way that I could generate this automatically without using the replace command like this:

    replace dist_skole_hjem = 55 if postnummer == 2 & skolepostnr =="3"

    So if there is some way that I could get stata to automatically fill out the dist_skole_hjem variable with the information from my dist_1, dist_2, dist_3 etc using the variables postnummer and skolepostnr and obtain the same as if I used the replace command?

    Hope you can help me!

    Last edited by Louise Henriksen; 24 Feb 2020, 05:43.

  • #2
    Please read and act on FAQ Advice #12 on presenting data.

    is this what you want?

    Code:
    clear
    input float(postnummer dist_1 dist_2 dist_3 skolepostnr)
    1 20.5 40.7 90 1
    2   45  120 55 3
    end
    
    gen wanted = .
    
    forval j = 1/3 {
        replace wanted = dist_`j' if skolepostnr == `j'
    }
    
    list
    
         +---------------------------------------------------------+
         | postnu~r   dist_1   dist_2   dist_3   skolep~r   wanted |
         |---------------------------------------------------------|
      1. |        1     20.5     40.7       90          1     20.5 |
      2. |        2       45      120       55          3       55 |
         +---------------------------------------------------------+

    Comment


    • #3
      Thank you, this was very helpful!

      Comment

      Working...
      X