Announcement

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

  • Replace String Observations with String Observations

    This is basic and I'm getting something wrong.

    Goal:
    If the response in the variable "Type" is "Other",
    then replace the word "Other" in the variable "Type" with the response in the variable "Type_if_Other"


    Data Sample:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input int Plan str53 Type str22 Type_if_Other
       1 "Other"                                                 "Unknown"               
       4 "PPO"                                                   ""                      
      27 "Other"                                                 "QHDHP w/ HRA"          
     189 "Other"                                                 "PPO w/FSA"             
     885 "Other"                                                 "EPO"                                     
    1052 "Other"                                                 "non-qualified HDHP PPO"
    1787 "PPO"                                                   ""                      
    1803 "PPO"                                                   ""                      
    end

    Based on code that has worked in the past using numeric data, I've tried

    replace Type = Type_if_Other if Type == "Other"

    for which Stata responds with

    varlist required
    r(100);


    I've serached Statalist for previous questions and responses, but those seem to need to use destring, etc. In this case, I want to keep the string as a string.
    I've looked at the "24 Working with Strings," and it doesn't address replacing a string with a string (as far as I can tell).

    Thanks for any guidance you can give.



  • #2
    there must be something else going on that you are not telling us because this worked fine for me:
    Code:
    . replace Type = Type_if_Other if Type == "Other"
    (5 real changes made)

    Comment


    • #3
      Ah! Thank you, Rich Goldstein! I don't know what else was going on, but it must have been something elsewhere in the foreach loop (of which this is one step).

      There was a second "replace" at the end of the foreach ( code: save "`file'", replace), but I hadn't changed that code at all.

      After you confirmed that string replace (above) was working, I reopened the file, reentered the string replace command, and the code ran without a hitch.

      I don't know what I must have unknowingly changed elsewhere in that foreach loop, but knowing the string replacement code worked helped me stop trying to fix what was not broken! Phew.
      thanks.
      Last edited by James Voss; 11 Mar 2024, 13:30.

      Comment

      Working...
      X