Announcement

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

  • strings variables: Remove spaces in strings

    Hi everyone, I would like to remove any spaces existing in one of my variables, please. How can I do that?
    Look at my data below for variable "fuel". I have two "Ds" and two "Gs", but should have only one each:

    Code:
    . tab fuel
    
    G/D | Freq. Percent Cum.
    ------------+-----------------------------------
    D | 24,452 53.63 53.63
    D | 8 0.02 53.65
    Elc | 120 0.26 53.91
    Elec | 10 0.02 53.93
    G | 20,709 45.42 99.35
    GLP | 1 0.00 99.35
    G | 2 0.00 99.36
    H | 294 0.64 100.00
    ------------+-----------------------------------
    Total | 45,596 100.00


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str4 fuel
    "G"
    "G"
    "G"
    "G"
    "G"
    end
    Could anyone help me, please? I already tried -strltrim(fuel)-, -strtrim(fuel)- and -ustrrtrim(fuel)-, but doesn't work.
    Thank you for your feedback!

    Michael
    Last edited by Michael Duarte Goncalves; 18 Dec 2023, 02:29.

  • #2
    Code:
    replace fuel= ustrtrim(fuel)
    tab fuel
    Otherwise, if the above does not solve the problem, show us the result of:

    Code:
    dataex fuel if ustrregexm(fuel, "D|G") & (fuel!="D"| fuel!="G")
    You can also take a look at chartab from SSC to see all characters that are present in the string and delete the unwanted characters specifically.

    Code:
    ssc install chartab, replace
    chartab fuel

    Comment


    • #3
      Hi Andrew Musau,

      Everything works perfectly with the first option in #2:

      Code:
      replace fuel = ustrtrim(fuel)
      tab fuel
      
      
              G/D |      Freq.     Percent        Cum.
      ------------+-----------------------------------
                D |     24,460       53.65       53.65
              DyE |         41        0.09       53.73
              Elc |        120        0.26       54.00
             Elec |         10        0.02       54.02
                G |     20,087       44.05       98.07
              GLP |          1        0.00       98.08
              GyE |        246        0.54       98.62
               HE |          7        0.02       98.63
                M |        263        0.58       99.21
                S |        361        0.79      100.00
      ------------+-----------------------------------
            Total |     45,596      100.00
      Thank you so much for your help!
      I wish you a lovely day.

      Comment

      Working...
      X