Q:

Loop over string vector for graphs in R

I'd like to loop over a string vector called country, which contains country codes, such as AFG, ETH, etc. 
In Stata the code would look like this: 
levelsof country, local(xtry)
foreach x in local xtry:
 graph command here if xtry=="`x'"
 graph save mygraph

}

Is there a comparable command to levelsof, as well an "if" statement that restricts the data to a particular country code, which is a string, from which each graph will be created?

A:

You would use something like this:
for (cn in levels(country))
    {
    if (cn=="x")
       {
       <do something>
       }
    else
       {
       <do something else>
       }
    }

If you want to check for multiple countries you can use
if (cn == "x" | cn == "y")

or also
if (cn %in% c("x", "y", "z"))

