Piomicron
Piomicron

Reputation: 113

How can I plot variables in a for loop in R?

So, I'm trying to make a plot in the following format:

print(levelplot(Z ~ X*Y, data=data))

X and Y are column names in the dataframe. If I have a list of the column names, how can I go through them and plot every column against every other column?

Upvotes: 0

Views: 71

Answers (1)

langtang
langtang

Reputation: 24722

If you have a vector of colnames, say cols, you can loop over all the combinations of those column names, each time creating the plot, like this:

plots = lapply(combn(cols,2,simplify = F), function(v) {
  levelplot(as.formula(paste0("Z~",v[1],"*",v[2])), data=d)
})

Now, plots is a list of levelplot() objects, which you can then plot, for example, like this:

gridExtra::grid.arrange(plots[[1]], plots[[2]])

Upvotes: 1

Related Questions