Announcement

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

  • Substr/Strlen Issue

    Hello Statalisters,

    I have an issue trying to use substr to split an existing variable. I have a variable County2 which looks like:

    CountyMT
    CountyMI
    CountyVA
    CountyTX

    and so on. I've generated a new variable named StateAbbr using
    generate str1 StateAbbrv = " "
    and now have a blank variable ready for input. From what I've read I believe I should be able to replace the new variable with just the state abbreviations using something like
    replace StateAbbrv= substr(County2, 1, strlen(County2)-6)
    but this just keeps the Co part of the original County2 variable, not the two letter state abbreviation at the end. Should it be a +6 instead or am I approaching this the wrong way altogether?

  • #2
    You want

    Code:
    replace StateAbbrv = substr(County2, -2, .)

    By the way, you could just start with

    Code:
    generate StateAbbrv = substr(County2, -2, .)
    right away.

    If you expect some non-ASCII characters (unlikely in English), use usubstr() instead.

    Comment


    • #3
      Thanks, daniel. That worked a treat.

      Comment

      Working...
      X