Loop over string vector for graphs in R

I would like to iterate over a named string vector country

that contains country codes such as AFG

, ETH

etc.

The Stata

code will 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 for levelsof

as well as an if statement that restricts the data to a specific country code, which is the string from which each graph will be generated?

+3
string r graph stata


source to share


2 answers


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 multiple countries, you can use



if (cn == "x" | cn == "y")

      

and

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

      

+3


source to share


As an aside, the applied group of functions is really similar, if not identical to the design for loops, the fact is that the applied group of functions is a wrapper for such loops and is specific to different data structures and requirements - more Rish-image makes loops. I don't know how valid the speed increase requirements are - I am skeptical. Other than that, if I understand what you are asking (I don't know stata), it might be easier to multiply the data with R and then do multiple plots for each subset.



0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics