Announcement

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

  • Assigning value from one variable to another if condition is met

    I have a data manipulation question:
    I have a dataset with the variables "id_1", "year", and "id_2." I would like to create a new variable "year_new" that takes the value of the variable "year" in row 1, if "id_2" has the same value as id_1 in row 1. Essentially, "year_new[_n]" (in row _n) is assigned the value of "year[_n-x]" if "id_2[_n]" = "id_1[_n-x]", where x is some number.

    Code:
    id_1 year id_2 year_new
    909 2019   2  .
      .    . 909   2019
    Thank you for your help!
    Last edited by Hans Zimmer; 30 Dec 2022, 13:30.

  • #2
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(id_1 year id_2)
    909 2019   2
      .    . 909
    end
    
    frame put id_1 year, into(source)
    frlink m:1 id_2, frame(source id_1)
    frget year_new = year, from(source)
    drop source
    frame drop source
    In the future, when showing data examples, please use the -dataex- command to do so, as I have here. If you are running version 17, 16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    Comment


    • #3
      Thank you very much, Clyde! Works like a charm -- and a nice reminder that frames work well for this sort of thing.

      Comment

      Working...
      X