I have three different data.frames (GRCYPT_flows, ESIEIT_flows, GRCYPT_flows) which contain the same variables (report_ctry, partner_ctry, indicator, year, value), but with different levels/observations. Now I want to create plots for each of those data.frames. Since the plots are supposed to look the same, I seems reasonable to use an iterative command. I tried the foreach loop:
foreach(i=GRCYPT_flows, ESIEIT_flows, GRCYPT_flows) %do% { ggplot(i, aes(year, value)) +
geom_line(aes(colour=partner_ctry, linetype=indicator)) + facet_wrap(~report_ctry) +
theme(axis.text.x=element_text(angle=90, vjust=0.5)) +
scale_x_continuous(breaks=seq(2002, 2012, 2), name="") +
scale_y_continuous(name="Billion Euros") +
scale_colour_discrete(breaks=c("EA17", "ROW_NON_EA17"), labels=c("EA17", "Extra-EA17")) +
scale_linetype_discrete(breaks=c("EA17", "ROW_NON_EA17"), labels=c("Trade", "Capital")) +
theme(legend.title=element_blank())}
The code, as it is, does not work. I face to problems here:
Assign a data.frame to an iteration variable.
Tell the foreach loop to save each iteration to a different list with a distinct name (plot1, plot2, plot3, etc.).
I'm relatively sure, this is quite easy so solve if you have some experience with R. I'm a total greenhorn, however, so I really don't know where to start (I could easily do it with Stata with which I have at least some experience).
What I want to do is tell R: "Make a plot for each of these data.frames and save each of it in an individual list."
foreach
instead of a simplefor
(or list+lapply) – talatforeach
and useget
to fetch the actual data.frame. You can return a list usingforeach
infrastructure (e.g. see here). – Roman Luštrik