Announcement

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

  • Replace when a string variable is longer than 4 characters

    Dear all,

    I would like to replace a string variable which is longer than 4 digits with numbers. For example, if variable A has "swimming", "karate", "kickboxing", "basketball" then I want to change them into number 4 as they are longer than 4 characters. But not for "car" as it is shorter than 4.

    Many thanks in advance. Kim

  • #2
    It is not possible in Stata for the same variable to have both numerical and string values. This is one of many ways in which Stata is different from a spreadsheet.

    The closest you can come to this is replace those values of the string variable with "4", which is a one-character string containing the character '4'.

    Code:
    replace my_variable = "4" if strlen(my_variable) > 4
    -strlen()- is a Stata function that takes a string variable as argument and returns the number of characters in it. If your string variable contains Unicode characters, use -ustrlen()- instead.

    Comment


    • #3
      Dear Clyde, Thank you very much for your kind reply. It is really helpful. BW Kim

      Comment

      Working...
      X