Samuel Mehr
Samuel Mehr

Reputation: 23

Create a ton of plots in R via a loop

I'm a Stata power user and R newbie having trouble getting loops to work properly in R. Basically I have a bunch of columns in a dataframe that I want to create a series of pirateplots with.

I tried

mycols <- c("column1","column2","column3")
for (i in mycols){
  filename <- paste("~/Desktop/",i,".pdf",sep="")
  pdf(filename)
  pirateplot(formula = i ~ xvar,
             data = df)
  dev.off()
}

and have also tried replacing c("column1","column2","column3") with the actual column names, i.e. c(column1,column2,column3) but that doesn't work either. Is there not a simple way to refer to an item in a list? It seems like R treats strings and variable names as different things, reasonably, but I can't seem to find documentation for how to deal with this exceedingly simple case.

In Stata this would be far simpler, something like

foreach v of varlist column1-column3 {
   loc filename = "`v'plot"
   scatter `v' xvar, name("`filename'")
}

Thanks in advance for your help.

Upvotes: 2

Views: 82

Answers (1)

eipi10
eipi10

Reputation: 93871

The code will work if the entire formula is entered as a single string, which can be created using paste. Here's a reproducible example with the built-in mtcars data frame:

library(yarrr)

mycols <- c("wt","vs","hp")

for (i in mycols){

  filename <- paste(i, ".pdf", sep="")

  pdf(filename)
  pirateplot(formula = paste(i, "~ mpg"), data = mtcars)
  dev.off()
}

You code is producing a formula like the following each time through the loop:

pirateplot("column1" ~ xvar, data=df)

which is equivalent to the following in my example:

pirateplot("wt" ~ mpg, data=mtcars)

These generate this error:

Error in terms.formula(formula, data = data) : 
  invalid term in model formula

The formula needs to be either of class formula, like wt ~ mpg using bare column names, or a string, like "wt ~ mpg", which can be converted to a formula.

Upvotes: 2

Related Questions