Announcement

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

  • Changing specific cells with the number of the row in a loop command

    Hello everyone,

    I'm asking how can I replace the value of a specific cell with the number of the row in a loop command
    I've created a loop command to drop variables with missing values over than 20, and I want to count those variables that are dropped by generating a value called "missing_values" that supposed to have specific cells changing over the looping process.

    Example:

    foreach var of varlist ..... {
    count if missing(`var')
    if r(N)>20 drop `var'
    replace missing_values=_n in (_n/_N)
    }

    Any help?

  • #2
    I am not clear what you want here. Perhaps it is more like this:

    Code:
    gen missing_values = 0
    
    foreach var of varlist ... {
          count if missing(`var')
          if r(N) > 20 {
                  replace missing_values  = missing_values + missing(`var')
                  drop `var'
           }
    } 
    What should be clear is that once have dropped a variable, it is too late to recall any information about the pattern of missing values in that variable.

    Conversely, if the number of variables dropped is the focus, a variable is not needed.

    Code:
    local dropped = 0
    
    foreach var of varlist ... {
          count if missing(`var')
          if r(N) > 20 {
                  local dropped = `dropped' + 1 
                  local gone `gone' `var' 
                  drop `var'
           }
    }
    
    di "`dropped' variables dropped" 
    di "`gone' dropped" 
    In fact you could just accumulate the list of variables dropped and count it when done.
    Last edited by Nick Cox; 05 Dec 2022, 13:19.

    Comment


    • #3
      That's amazing !!!

      It worked better than I've even imagined!!

      Thanks a lot, sir.

      I really appreciate it.

      Comment


      • #4
        Another question if you allow me,

        Why did we write local gone `gone' 'var' instead of local gone= 'var' ?

        Comment


        • #5
          ... because I was accumulating the names of variables that had been dropped on the grounds that there might be two or more.

          Your code in #4 would report only the name of the last variable dropped, which would be fine if there were only one such variable.

          Comment

          Working...
          X