Pass multiple column name variables to interaction function in aes mapping

I would like to pass column name variable vectors to interaction function in aes mapping, but following code does not work. How can I implement this?

llibrary(dplyr)
library(ggplot2)

## Sample data
a <- seq(-10, 10)
df <- tibble(A=a, B=tan(a),
             C=LETTERS[1: length(a)],
             D=rev(letters[1: length(a)]),
             E=rep('E', length(a)),
             F=rep('F', length(a)))


## This works
df %>%
    ggplot(aes(x=A, y=B, colour=interaction(C, D))) +
    geom_point()


## How to pass multiple column names to interaction function in aes mapping?
column_names_variables <- c('C', 'D') ##  length differ case-by-case. It could be as c('C', 'E', 'F').



## Following does not works...
df %>%
    ggplot(aes(x=A, y=B, colour=interaction({{column_names_variables}})))
## + Error in `geom_blank()`:
## ! Problem while computing aesthetics.
## ℹ Error occurred in the 1st layer.
## Caused by error in `check_aesthetics()`:
## ! Aesthetics must be either length 1 or the same as the data (21)
## ✖ Fix the following mappings: `colour`
## Run `rlang::last_trace()` to see where the error occurred.

replace these with !!!syms


ggplot(
  df,
  aes(
    x = A, y = B,
    colour = interaction(!!!syms(column_names_variables))
  )
) +geom_point()
1 Like

@nigrahamuk,

Thanks for elegant solutions, it works!! I did not know that expression, I will learn about 19 Quasiquotation | Advanced R.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.