Announcement

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

  • How can I define a variable in terms of its relative position to another variable?

    Hi all,

    I will really appreciate your help in this matter.

    I would like to know how can I define a variable using its relative position to another variable? For example, lets say I have the variables: A B C D E, and I would like to apply the command "keep B-D" (without the quotes). However, what I would like to be able to write is something like "keep B-B[,3]", or similar. Is something like this even possible in Stata?

    Thank you very much in advance for your help.

  • #2
    Welcome to Statalist.

    Here's some technique using extended macro functions that can accomplish what you hope for.
    Code:
    . describe, simple
    a  b  c  d  e
    
    . local vfirst b
    
    . local vnum 3
    
    . 
    . unab vars : *
    
    . local pfirst : list posof "`vfirst'" in vars
    
    . local plast = `pfirst' + `vnum' - 1
    
    . local vlast : word `plast' of `vars'
    
    . 
    . keep `vfirst'-`vlast'
    
    . describe, simple
    b  c  d
    For more details, see the output of help extended_fcn and help macrolists.

    And for something a little fancier, you can create a program and use it repeatedly in your do-file.
    Code:
    capture program drop mykeep
    program define mykeep
    unab vars : *
    local vfirst `1'
    local vnum `2'
    
    local pfirst : list posof "`vfirst'" in vars
    local plast = `pfirst' + `vnum' - 1
    local vlast : word `plast' of `vars'
    
    keep `vfirst'-`vlast'
    end
    
    describe, simple
    mykeep b 3
    describe, simple
    Code:
    . describe, simple
    a  b  c  d  e
    
    . mykeep b 3
    
    . describe, simple
    b  c  d

    Comment


    • #3
      Thank you very much for your Willian.

      Comment

      Working...
      X