Announcement

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

  • Able to numerically encode some, but not all, values of a string variable

    [Transferred from here.]

    Originally posted by Yankuba Jarjusey View Post
    Thank you for helping me to better frame the question.
    The variable is a string (str) with non-numeric characters: "Yes," "No," and "I don't know." I am assessing respondents' knowledge of hepatitis B virus curability, and the possible responses are "Yes," "No," and "I don't know."
    The responses "No" or "I don't know" should be scored "0." I received no red error message in the output window, but those characters were not replaced with "0."

    command in Stata 18, "replace Q2= "0" if Q2=="No" | Q2=="I don't know". All the "No" were replaced, but not the "I don't know" responses.
    In the output window/panel, below the command lines, it says "0 real changes made," and I confirmed this by tabulating the variable containing such responses. The responses were still the same because they were not replaced with the "0s" I wanted.

    I hope I have provided enough information to better describe the issue I am facing now. I appreciate your swift response, Mr. Schechter.

  • #2
    Stata wants to see "I don't know" and anything else similar but not identical is ignored. Some possible problems are

    leading and trailing spaces

    upper and lower case inconsistency

    other punctuation e,g, missing apostrophes

    Show us the results of

    Code:
    tab Q2 if strpos(lower(Q2), "know")
    or experiment similarly.

    Comment


    • #3
      Oh, thanks so much, Nick. I have seen the problem now. There were trailing blanks, which I never knew about. I have seen the trailing blanks using the "codebook Q2" command. It was stored as "I don't know " instead of "I don't know".

      Comment


      • #4
        There were trailing blanks, which I never knew about.
        This, and leading blanks, are common problems in data sets with string variables. When I work with string variables, I usually deal with these by running:
        Code:
        replace var = trim(var)
        which removes both. If there are also excess internal blanks, also fairly common but a bit less so in my experience, those can be removed with:
        Code:
        replace var = trim(itrim(var))
        Both the -trim()- and -itrim()- functions leave the strings alone if they do not have any blanks. And they run quickly, even in very large data sets.

        Doing these things to your string variables from the beginning is less tedious and error-prone than writing a bunch of -replace- commands tailored to the specific instances of unwanted blanks.


        Comment

        Working...
        X