Help with automated ggplot2 in a nested loop

There are is a short thread of comments to the post you linked to that are relevant here. I think you could start here and then see the next in the thread for an example of working with three variables.

Essentially, I was being a bit tricky with that nested loop and being able to refer to .x. That trick quickly fails with more nesting.

I'd switch to using anonymous functions if you want more nested maps. Nested loops in general are a little hard to follow, but that could look something like:

map(demo, function(demo) {
    map(response,
        function(response) {
            map(expl, jitter_fun, y = response, z = demo)
            })
    })

It can be reasonable to forgo the complexity of nesting in some cases. The main reason I like nested loops (in some cases) is if I want to take advantage of the organization and list names in the output. If you don't need those, switch to crossing variables plus pmap() will make the code easier to read.

Like:

allvar = tidyr::expand_grid(expl, response, demo)
pmap(allvar, ~jitter_fun(x = ..1, y = ..2, z = ..3))

Use anonymous functions if you have more than 3 variables to pass into pmap() or if your variables are not in the same order as your function arguments.

I couldn't test these extensively without your dataset, but the code examples hit on the general idea. In the future, try including a minimal reproducible example when asking a question. :slight_smile: