Announcement

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

  • set string case to missing if a phrase is found

    Hello,

    I have a series of string variables (drug1 - drug25) that contain information on types of drugs. Below is an example of 2 of the variables and their contents:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str25 drug1 str27 drug2
    "Fentanyl (0.91)"    "Norfentanyl (0)"         
    "Fentanyl (2.25)"    "Norfentanyl (0.81)"      
    "MDMA (0)"           "Methamphetamine (20.98)" 
    "MDMA (0)"           "Methamphetamine (42.667)"
    "THC (3.29)"         ""                        
    "THC (48.51)"        ""                        
    "THC (24.5)"         ""                        
    "Hydrocodone (0)"    "Hydromorphone (0)"       
    "Norhydrocodone (0)" "Noroxycodone (0)"        
    "MDMA (0)"           "Methamphetamine (5.417)" 
    end
    What i want to do is whenever "(0)" appears, i want the contents of that cell set to missing or "". If it's anything other than "(0)" (e.g., 0.91) it's left alone.

    Any help would be greatly appreciated!

    Thanks

  • #2
    Code:
    formal I=1/25 {
       replace drug`i'="" if strpos(drug`i',"(0)")>0
       }
    but be careful to save under a different name as this will change your data

    Comment


    • #3
      Thanks for the data example. You can do this easily with regular expressions. If I've understood you correctly, this will do what you want.

      Code:
      forval i = 1/25 {
        gen want`i' = drug`i'
        replace want`i' = "" if ustrregexm(want`i', ".*\(0\)")
      }
      Edit: updated as I missed the loop requirement.
      Last edited by Leonardo Guizzetti; 07 Apr 2023, 12:46.

      Comment

      Working...
      X