Announcement

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

  • How to write a for-loop that subsets my data based on different values of a string variable

    I have what seems like a simple syntax issue that I can't figure out.

    I want to write a for-loop that subsets my data based on different values of a string variable.

    However, I keep getting a "type mismatch" error.

    Here is an example of my problem:
    Code:
    sysuse auto, clear
    foreach mk in "AMC Concord" {
        keep if make = "`mk'"
    }
    Any help would be much appreciated!

  • #2
    In that case the problem appears to be needing == not =.

    Supposing that your string variable has distinct values a b c d a problem is that you need to read in the dataset again.

    Why not use if for analysis or frames?


    Code:
    foreach v in a b c d {
         use mydata, clear
         keep if myvar == "`x'"
         save mydata_`x'
    }
    Last edited by Nick Cox; 23 Jan 2023, 12:11.

    Comment


    • #3
      To compare two values, use "==" not "=" which is used to assign a value to a variable.

      Code:
      . sysuse auto, clear
      (1978 automobile data)
      
      . foreach mk in "AMC Concord" {
        2.     keep if make == "`mk'"
        3. }
      (73 observations deleted)
      
      .

      Comment


      • #4
        Ah, that was a dumb mistake! Thanks Nick Cox and William Lisowski for pointing it out!

        Comment

        Working...
        X