Announcement

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

  • Add prefix to all variables except one (or two)

    Let's say I had a dataset with 100 variables, and I wanted to add a prefix (let's say "use_") to all variables except one or two of them. What would be the easiest way to do that other than simply creating a varlist with all 98 variables listed out?

  • #2
    Code:
    version 18.0
    
    quietly sysuse auto, clear
    
    *
    * Begin here
    *
    quietly ds _all
    local varlist `r(varlist)'
    
    local exclude rep78 gear_ratio
    local varlist : list varlist - exclude
    
    rename (`varlist') use_=
    
    exit

    Comment


    • #3
      Originally posted by Dakota McAvoy View Post
      What would be the easiest way to do that other than simply creating a varlist with all 98 variables listed out?
      You''re not going to be able to avoid traversing the list of ninety-eight variable names in some manner, but you could do something like the following that disguises that.
      Code:
      quietly sysuse autos, clear
      
      foreach var of varlist _all {
          if inlist("`var'", "rep78", "gear_ratio") continue
          rename `var' use_`var'
      }
      
      exit

      Comment


      • #4
        Here's a more direct way to do it, building on Joseph Coveney 's very helpful example:

        Code:
        sysuse auto, clear
        
        ds rep78 gear_ratio, not
        
        rename (`r(varlist)') use_=
        
        ds use_*
        Clearly you already have your dataset and just need to change rep78 gear_ratio to the one or two names you wish to exclude.
        Last edited by Nick Cox; 27 Mar 2024, 03:17.

        Comment

        Working...
        X