Announcement

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

  • Spaces in imported variable names

    I am importing the attached excel file, as follows:
    Code:
    import excel "Year-round trends\SASS NTPS trends\National trends, values.xlsx", sheet("Nationwide percentages") firstrow clear
    By default a column header like "pct year-round single track" turns into the variable name pctyearroundsingletrack (with no spaces), which is not very readable.

    I would prefer to replaces the spaces with underscores, like this: pct_year_round_single_track
    Is there a way for Stata to do that?

    Thanks!
    Paul
    Attached Files
    Last edited by paulvonhippel; 12 Aug 2022, 01:38.

  • #2
    I don't see any option to import excel that would allow that, but you can use SQL to rename your variables on-the-fly via ODBC. Something like the following:
    Code:
    version 17.0
    
    clear *
    
    #delimit ;
    local sql_statement SELECT [School year] AS school_year, Survey, Note,
        [pct year-round] AS pct_year_round,
        [pct year-round single-track] AS pct_year_round_single_track,
        [pct year-round multi-track] AS pct_year_round_multi_track FROM [Sheet1$];
    #delimit cr
    
    local dsn Excel Files;DBQ=National trends, values.xlsx;DefaultDir=`c(pwd)'\;
    
    odbc load, exec("`sql_statement';") dsn("`dsn'")
    
    exit
    Illustrated for Microsoft Windows operating system (you'll need to set up ODBC if you haven't already done so).

    Comment


    • #3
      Code:
      import excel "Year-round trends\SASS NTPS trends\National trends, values.xlsx", sheet("Nationwide percentages") firstrow clear
      
      foreach var of varlist * {
          local lab: var label `var'
          local varname = subinstr("`lab'"," ","_",.)
          local varname = subinstr("`varname'","-","_",.)
          rename `var' `varname'
      }

      Comment


      • #4
        For the approach outlined in #3, also see

        Code:
        help strtoname()

        Comment

        Working...
        X