Announcement

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

  • Dropping all the variables that are positioned after a variable.

    Hi,

    I would like to drop all the variables that are positioned after a given variable of my dataset. I saw that I could use the absolute position of a variable to get rid of it, for instance by using the command -tokenize-. However I'm using a loop to work on several dataset and the absolute position of a variable can vary from one dataset to another. But the variables I want to drop are always located after a certain variable called varX. So I would like to use a command to drop variables based on their relative position to varX.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str3(var1 var2 var3 varX varY varZ)
    "123" "222" "332" "124" "554" "777"
    "217" "232" "67"  "12"  "332" "83"
    end
    I made this example up to be more clear. I would like to to drop variables that are located AFTER varX, namely varY and varZ. But I cannot use a command that would ask Stata to drop the 5th and the 6th variable because they do not always have this position in my many datasets. So just "all the variables after varX" would do the job.

    Thank you in advance for your help.

  • #2
    Code:
    unab vars: *
    local first: word 1 of `vars'
    keep `first'-varX
    alternatively:

    Code:
    unab vars: *
    local lastnum: list sizeof vars
    local varX_pos: list posof "varX" in vars
    local nextvar: word `=`varX_pos'+1' of `vars'
    local lastvar: word `lastnum' of `vars'
    drop `nextvar'-`lastvar'
    Last edited by Hemanshu Kumar; 16 Jan 2023, 02:42.

    Comment


    • #3
      An alternative:
      Code:
      gen AfterVarXWhere = ., after(varX)
      gen LastWhere = .
      
      drop AfterVarXWhere-LastWhere

      Comment


      • #4
        Code:
        mata: st_dropvar(st_varindex("varX")+1..st_nvar())
        Assumes that varX is never the last variable.

        ​​​​
        Code:
        mata : st_keepvar(1..st_varindex("varX"))
        is an obvious alternative.
        Last edited by daniel klein; 16 Jan 2023, 05:37.

        Comment


        • #5
          daniel klein I think #4 needs the addition of 1 to the index of varX; otherwise varX will be dropped itself.

          Comment

          Working...
          X