Announcement

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

  • Replacing values in a variable

    Hello everyone.

    I am trying to replace the values in an old variable with ones from a new variable. The new variable only appears in the dataset if a person wants to update their information otherwise there will be no variable generated. This new variable takes on the same name as old variable but ends with a suffix '_n'.

    Example:
    Old variable: education
    New Variable: education_n

    The idea is that if the dataset has the occurrence of a new variable, then replace values of old one with new one for all non-missing occurrences. This is more like automating a task so that I do not have to manually enter the variables each time.


  • #2
    Code:
    foreach new of varlist *_n {
        local old : subinstr local new "_n" ""
        replace `old' = `new' if !mi(`new')
    }
    You might want to consider keep both variables as-is, and creating a third.
    Code:
    generate double `new'_u = cond(!mi(`new'), `new', `old')

    Comment


    • #3
      Joseph Coveney thank you for this! will give it a try

      Comment


      • #4
        Just thought i should update this post here. So I tried the code however, i came across an issue where if there was _n anywhere in the variables name, it would be replaced with empty string which was affecting the replace function. I then modified your code to address this. It is as follows:

        Code:
            rename *_n test*, r dryrun
            foreach new in `r(oldnames)' {
                local old = substr("`new'", 1 , strrpos("`new'", "_")-1)
                replace `old' = `new' if !missing(`new')
            }
        Instead I start off by identifying all those variables ending with _n only, then used substring to extract the relevant part to be considered as the old variable and then replaced accordingly.

        Nevertheless you code helped me understand how to think about such problems. So thank you for that!

        Comment

        Working...
        X