Announcement

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

  • Storing and displaying multiple (>10) string values that begin with a blank character in a local macro.

    Hello,

    I want to use a local macro in a loop (foreach) that will eliminate the specified characters (including blank spaces) from matching string values in a variable. I have been trying to store multiple string values that begin with a blank space (i.e. " ST" " AV" " BLVD" ...) into a local macro. After executing the macro command the display command shows nothing, and the loop will not process the data (no output). I am using Stata_IC v.13.1 and the code is:

    local suffix1Y `" " ST" " AV" " BLVD" " DR" "'
    disp `suffix1Y'

    foreach s of local suffix1Y {
    replace Bus_1Y5 = regexr(Bus_1Y5,"`s'$","")
    }


    I also tried storing the string values with no beginning blank spaces and adding a blank space in the regexr command (...," `s'$",...) but did not work either.

    Is the problem one of syntax? I have looked at several guidelines and literature about storing string values but none seem to address this situation with beginning blank characters.

    Thank you,

    Enrique

  • #2
    Welcome to Statalist, Enrique.

    This seems to do what you want.
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str20 Bus_1Y5
    "A ST"  
    "BB AV"  
    "CCC BLVD"
    "DDDD DR"  
    end
    local suffix1Y ST AV BLVD DR
    foreach s of local suffix1Y {
    replace Bus_1Y5 = regexr(Bus_1Y5," `s'$","")
    }
    generate lb = length(Bus_1Y5)
    list, clean noobs
    Code:
    . list, clean noobs
    
        Bus_1Y5   lb  
              A    1  
             BB    2  
            CCC    3  
           DDDD    4

    Comment


    • #3
      Another way to think about it (no loops and no macros needed):

      Code:
      replace Bus_1Y5 = substr(Bus_1Y5, 1, strrpos(Bus_1Y5, " ") - 1) if inlist(word(Bus_1Y5, -1), "ST", "AV", "BLVD", "DR")
      In words: Replace the variable with everything up to just before the last space if its last word is one of the values ST AV BLVD DR.

      Comment


      • #4
        Excellent, thank you both; the two options work.

        Enrique

        Comment

        Working...
        X