Announcement

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

  • How to shift all values in an existing variable by one row?

    Hi. I am currently dealing with some time series data, and would like to create a new variable equal to an existing variable's value but shifted up by one row. Is there any code could accomplish this action?

  • #2
    ...but shifted up by one row
    I don't know whether that means that the new variable's values are the same as those of the old variable in the observation ("row") just above, or the same as those in the observation just below.
    Code:
    gen new_variable = original_variable[_n+1]
    gen new_variable = original_variable[_n-1]
    Anyway, one of the two commands shown just above will do it, depending on which interpretation you meant.

    In the future, when asking for help with code, please use the -dataex- command and show example data. Although sometimes, as here, it is possible to give an answer that has a reasonable probability of being correct, this is usually not the case. Moreover, such answers are necessarily based on experience-based guesses or intuitions about the nature of your data. When those guesses are wrong, both you and the person trying to help you have wasted their time as you end up with useless code. To avoid this, a -dataex- based example provides all of the information needed to develop and test a solution.

    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.

    When asking for help with code, always show example data. When showing example data, always use -dataex-.
    Last edited by Clyde Schechter; 08 Apr 2023, 22:50.

    Comment

    Working...
    X