0

Using a forvalues loop, I am merging a list of 400 individual datasets.

These datasets can be one of 10 distinct values (defined by a variable in the dataset): depending on the dataset, I would merge with a different dataset. For example, if Player 90 was type 9, I would want to merge with Type_9.dta rather than Type_8 or Type_7.

What I want is something like this:

forvalues x = 1/400 {
    use "player_`x'.dta"

    * some way to turn the value of player type into a local macro l *

    merge 1:1 using "type_`l'.dta"
}

How can i get the variable type into a macro that changes for each type through the loop?

1 Answers1

1

The structure of your data and the ultimate goal are not quite clear to me, so there may be more efficient ways to do that.

If player_type does not vary within each player_* data set, you can use levelsof. This has the feature that if player_type varies for some reason like a data entry error, the loop will error out.

forvalues x = 1/400 { 
   use "player_`x'.dta"
   levelsof player_type, local(l)
   merge 1:1 **some_id_var** using "type_`l'.dta" 
}
dimitriy
  • 9,077
  • 2
  • 25
  • 50
  • This isn't clear to me either: for example, if you have already `merge`d one dataset, what is to stop that being done again? But if `player_type` is constant, it will suffice to use the value of `player_type[1]`, so no need to fire up `levelsof`. – Nick Cox Jun 25 '13 at 17:37
  • I used `levelsof` because the loop will break if `player_type` is not in fact constant. – dimitriy Jun 25 '13 at 18:13
  • 1
    Fine; I see that now. Better to spell that out in a revision of your answer? – Nick Cox Jun 25 '13 at 18:16