tags:

views:

176

answers:

1

I have a set of survey data, and I'd like to generate plots of a particular variable, grouped by the respondent's country. The code I have written to generate the plots so far is:

countries <- isplit(drones, drones$v3)
foreach(country = countries) %dopar% {
  png(file = paste(output.exp, "/Histogram of Job Satisfaction in ", country$key[[1]], ".png", sep = ""))
  country.df <- data.frame(country)  #ggplot2 doesn't appreciate the lists nextElem() produces
  ggplot(country.df, aes(x = value.v51)) + geom_histogram()
  dev.off()
}

The truly bizarre thing? I can run the isplit(), set country <- nextElem(countries), and then run through the code without sending the foreach line - and get a lovely plot. If I send the foreach, I get some blank .png files.

Thanks in advance for your help.

I can definitely do this with standard R loops, but I'd really like to get a better grasp on foreach.

+6  A: 

You need to print the plot if you want it to display:

print(ggplot(country.df, aes(x = value.v51)) + geom_histogram())

By default, ggplot commands return a plot object but the command itself does not actually display the plot; that is done with the print command. Note that when you run code interactively, results of commands get printed which is why you often don't need the explicit print. But when wrapping in a foreach, you need to explicitly print since the results of the commands in the body will not be echoed.

Jonathan Chang
Alternatively, use `ggsave`
hadley
Jonathan, thank you for the explanation - that will likely save me confusion in the future, too. Hadley, thanks for mentioning (uh, and writing) ggsave() - it's smooth.
Matt Parker