Announcement

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

  • Replace using patterns

    Hello everyone,
    I am dealing with a dataset that has variable names with the same prefix. I would like to move the contents of one variable to another using that prefix as a pattern.
    Let's say I have the following varnames:

    var1_x var2_x var3_x var1_y var2_y var3_y

    I would like to move the contents from *_x to *_y.

    I thought using a foreach or replace could solve the problem, like the following: replace *_y = *_x
    But it does not work. Sure I am doing something wrong. Do you know if there is a better way?

    Thank you so much!


    David



  • #2
    Why not simply drop the *_y variables and rename the *_x variables?

    Code:
    drop *_y
    rename *_x *_y
    If this is not what you want, we might need more details from your side.

    Comment


    • #3
      I am sorry I have not explained more details.
      This replace is only for specific observations (rows), and only for some variable names (not all of them share prefixes).
      So I was thinking about doing:

      replace *_y = *_x if id=="some_row"

      Thanks






      Comment


      • #4
        Originally posted by DF Moreno View Post
        This replace is [...] only for some variable names (not all of them share prefixes).
        This makes things more complicated. You need to get a list of prefixes that you want, then implement a loop:

        Code:
        local list_of_prefixes ...
        
        foreach prefix of local list_of_prefixes {
            
            replace `prefix'_y = `prefix'_x if exp
            
        }
        You might be able to get the list of prefixes from

        Code:
        unab list_of_prefixes : *_y
        but I cannot be sure.

        Also, your if condition, despite being pseudo-code, looks rather ad-hoc. It is usually better to identify observations by conditions, e.g., if missing(prefix_x), than referring to some ID variable.

        Comment


        • #5
          That worked perfectly!

          Thanks

          Comment

          Working...
          X