1

This works:

plot_interaction_term = function(df)
{
  print(ggplot(data=df, mapping=aes(y=new_confirmed, x=cumulative_vaccine_doses_administered_pfizer, color=cut(cumulative_vaccine_doses_administered_moderna, breaks=c(-Inf, Inf)))) 
        + geom_point()
        + geom_smooth(method = "lm", se=FALSE))
}

plot_interaction_term(df)

This doesn't work:

plot_interaction_term = function(df, explanatory_variable1, explanatory_variable2)
{
  print(ggplot(data=df, mapping=aes(y=new_confirmed, x=explanatory_variable1, color=cut(explanatory_variable2, breaks=c(-Inf, Inf)))) 
        + geom_point()
        + geom_smooth(method = "lm", se=FALSE))
}

plot_interaction_term(df, "cumulative_vaccine_doses_administered_pfizer", "cumulative_vaccine_doses_administered_moderna")

ERROR: Error in cut.default(explanatory_variable2, breaks = c(-Inf, Inf)) : 'x' must be numeric

2nd try:

plot_interaction_term(df, cumulative_vaccine_doses_administered_pfizer, cumulative_vaccine_doses_administered_moderna)

ERROR: Error in FUN(X[[i]], ...) : object 'cumulative_vaccine_doses_administered_pfizer' not found

3rd try:

plot_interaction_term(df, df["cumulative_vaccine_doses_administered_pfizer"], df["cumulative_vaccine_doses_administered_moderna"])

Error in cut.default(explanatory_variable2, breaks = c(-Inf, Inf)) : 'x' must be numeric

How do I get this to work?

print(df)

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
NoName
  • 9,824
  • 5
  • 32
  • 52

1 Answers1

2

We can use .data

plot_interaction_term = function(df, explanatory_variable1, explanatory_variable2)
{
  print(ggplot(data=df, mapping=aes(y=new_confirmed, x=.data[[explanatory_variable1]], color=cut(.data[[explanatory_variable2]], breaks=c(-Inf, Inf)))) +
        geom_point() +
         geom_smooth(method = "lm", se=FALSE))
}
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Can you explain what is happening in the syntax `.data[[explanatory_variable1]]`? Intuitively, I would expect it to just be `data[explanatory_variable1]` where `data` is referring the to `df` object. – NoName Jun 26 '21 at 21:32
  • @NoName. the `[` is still a data.frame/tibble instead of a vector and `cut` requires a vector as input – akrun Jun 26 '21 at 21:34
  • @NoName It is not `data`, but `.data`, which is a data pronoun. For more info, you can check `?".data"` or `?"tidyeval-data"` – akrun Jun 26 '21 at 21:41