Announcement

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

  • How to count rows from one not empty row to the next not empty row between two different variables?

    Dear statalist,

    I have two variables (var1 and var2). Most of the observations in var1 and var2 are empty, but some also have values. I want to generate a third variable (var3) which shows how much rows are between a not empty value in var1 and the next not empty row of var2.

    The data looks like in the table below.The values of var1 and var2 are random and don't matter, it only matters if it is empty or not

    To explain the table:

    Row 2 is the first row which is not empty as there is 45. So I want to look for the next row (which could also be the same row) in var2 which is not empty. This is also row 2 as there is 1. So I would like to have 0 in var3 as it is in the same row.
    The next not empty row in var1 is row 4. The next row which is not empty in var2 is row 6. So I want to have 2 in var3 as the difference of the rows is 2.
    And so on for the other values.

    How can I code that var3 counts automatically these rows?
    Does anybody have recommendations how to do this?

    row var1 var2 var3 what var3 should be
    1
    2 45 1 0
    3
    4 700 2
    5
    6 20
    7
    8 2 1
    9 555


  • #2
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte row int(var1 var2)
    1   .   .
    2  45   1
    3   .   .
    4 700   .
    5   .   .
    6   .  20
    7   .   .
    8   2   .
    9   . 555
    end
    
    gen spell_num = sum(!missing(var1) | !missing(var2[_n-1]))
    by spell_num (row), sort: gen var3 = _N-1 if _n == 1 & !missing(var1[1])
    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

    Working...
    X