Announcement

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

  • Stata Recoding Variable Macro

    Hi all,

    I have a numeric variable, range is about from 100-400,000. I would like to recode this variable to group it into ranges of 1,000.
    For example:
    gen newvar = .
    replace newvar = 1 if var >=100 & <1000

    However, this will take a lot of time. I understand that a macro might help but I have zero experience with macros. I would appreciate any help in this. Thank you.

  • #2
    Here are a couple of ways to do this:
    Code:
    // Example data
    clear
    set seed 14876
    set obs 1000
    gen long x = trunc(100 + (400000-100) * runiform())
    // When stumped, always check out -help egen-
    egen trythis = cut(x), at(0(1000)500000) icodes  //500 to be safe
    replace trythis = trythis + 1
    // Do it yourself
    gen trythat = 1+ trunc(x/1000)

    Comment


    • #3
      By "macro" you mean perhaps routine or script or something similar. Stata's sense of the term macro is different, with two flavours local and global.

      Anyhow, I suggest one line of code

      Code:
      gen newvar = 1000 * ceil(var / 1000) 
      The prefactor 1000 is optional but it makes bins self-describing;

      See https://www.stata-journal.com/articl...article=dm0095 for an overview.

      Comment


      • #4
        Apart from what Mike and Nick showed (which are the easy and more natural Stata ways to accomplish the task), the loop is in green below
        Code:
        . clear
        
        . set obs 100000
        number of observations (_N) was 0, now 100,000
        
        . gen runiformint = runiformint(100,400000)
        
        . gen newvar = .
        (100,000 missing values generated)
        
        . qui forvalues i = 1000(1000)400000 {
        . replace newvar = `i' if runiformint<`i' & missing(newvar)
        . }

        Last edited by Joro Kolev; 02 Oct 2020, 12:41.

        Comment

        Working...
        X