Announcement

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

  • Invalid name error while using variable names in a loop

    Hello, I am trying to replace the missing values for all variables for an observation using the values from a subsequent observation. Below is the code that I am using.

    ds
    local allvar `r(varlist)'
    foreach cc of local allvar {
    bys id: replace "`cc'"[_n] = "`cc'"[_n+1] if dup == 1 & missing("`cc'"[_n]) & !missing("`cc'"[_n+1]) & check == 1 & max_dup == 2
    }

    When I run this code, however, I encounter an invalid name error shown here as: "date invalid name - date here is the first variable in my list of variables. Any and all help is highly appreciated.

  • #2
    Omit the double-quotation marks surrounding your variable name's local macro.
    Code:
    quietly ds
    foreach var of varlist `r(varlist)' {
        bysort id: replace `var'[_n] = `var'[_n+1] . . .
    }

    Comment


    • #3
      Originally posted by Joseph Coveney View Post
      Omit the double-quotation marks surrounding your variable name's local macro.
      Code:
      quietly ds
      foreach var of varlist `r(varlist)' {
      bysort id: replace `var'[_n] = `var'[_n+1] . . .
      }
      Thanks a ton! This worked.

      Comment


      • #4
        You can refactor the passage a little more, by omitting ds (unless you're selecting a subset of variables) and using the special constant _all instead. (I think an asterisk also works.)

        And although it probably isn't so great an inefficiency (because sort I think checks whether the dataset is already sorted), you can put the sort outside the loop and do it just once.
        Code:
        sort id <within-ID sequence variable>
        foreach var of varlist _all {
            by id: replace ...

        Comment

        Working...
        X