Announcement

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

  • Command/function to check that a variable is constant within groups before or within a collapse

    Hello!

    Its there in the subject line - I am curious whether there is a command or function I can use to check that a variable is constant within groups defined by another variable. I know how to do this with several lines of code but this is not neat enough. In my current context I want to do it before (or even within) a collapse.

    I will give a data example below but first here is one from my work: I am summing up income sources per individual. Each individual has a gender and these should in theory be constant by person identifier. I want to keep their gender but I have no easy way of confirming that there are not >1 gender value per person. I could use the mode or first non-missing but this requires assuming the data have no problems.

    I am aware of ways to count the number of genders per ID (with egen and tags) but this is quite painful to code and very slow to run. Ideally there would be an option in collapse as follows (example code):

    Code:
    collapse (sum) interest=total_interest wage=total_wage (constant) gender=gender, by(person_id)
    This could return an error if the gender is not constant across the rows within each group of person_id.

    What I am doing instead is first collapsing by person_id and gender, and then running the same collapse by just person_id. If the N changes this indicates that gender was not constant.

    In the data example below lets assume I want to aggregate the temp data to the division level, while keeping the region of that division. I would like to check that each division is associated with a single region.

    Code:
    sysuse citytemp4.dta
    
    collapse (sum) heatdd cooldd tempjan tempjuly (firstnm) region, by(division)
    Note how I am forced to use the firstnm option.

    Best,
    Bruce

  • #2
    https://journals.sagepub.com/doi/pdf...36867X20953578 reviews this problem.

    Comment

    Working...
    X