0

I have defined a function in a code chunk in R markdown. The goal is to create a line graph facetted by RACE variable.

{r, Helper function}
  line_graph_gender_race <- 
    function(data_new, xnew, ynew, titlenew, colornew, lwdnew, ylab, wrap) {
      line_graph_gender_race <- 
          ggplot(data = data_new,aes(x = xnew,y = ynew, color = colornew)) + 
          geom_line(lwd = lwdnew) + 
          labs(title = titlenew, y = ylab) + 
          facet_wrap(~wrap, nrow = 1, ncol = 2) + 
          theme(axis.text.x = element_text(angle = 45, vjust = 0.5))
      return (line_graph_gender_race)
    }

Next, we call this function in a different chunk;

{r, ref.label="Helper function"}

line_graph_gender_race(
  population_gender_race1_2,
  population_gender_race1_2$YEAR, 
  population_gender_race1_2$TOTAL_POP, 
  "Projected Population as Per Gender from July 1, 2012 through July 1,2060\n(White vs. Black Population)", 
  population_gender_race1_2$SEX, 
  2,  
  "Population Percent", 
  population_gender_race1_2$RACE
)

This facetting variable RACE is present. But we see an error:

At least one layer must contain all variables used for facetting

How can I solve this?

jay
  • 1,319
  • 6
  • 23
  • 42
  • 2
    proper code line breaks and indentation would go a long way towards both better coding in general and helping folks help you. but from the error message alone, you are missing data. we also don't have a minimal example of your data (that the SO R FAQ notes is a nigh requirement for a decent question and that you've also likely seen in dozens if not hundreds of good SO questions). – hrbrmstr May 25 '18 at 12:19
  • 1
    The problem is that `ggplot` works with data in a single data frame, but you are trying to pass in multiple vectors. In particular, it is complaining because there is no `wrap` variable in your data. Rewrite your function to accept a single data frame as the argument. I bet the column names are the same every time you call this. –  May 25 '18 at 12:32
  • @dash2. thanks for your feedback. That is true, I do not have any variable by the name 'wrap' in my data. That's why I am passing the variable, ```population_gender_race1_2$RACE``` to the variable ```wrap``` while calling the function. Is that syntax/approach wrong?Can you kindly comment? – jay May 25 '18 at 21:12
  • 1
    I tried to explain in my last comment. `ggplot` uses a single data frame, then looks in its columns for its arguments. So the `wrap` argument to `facet_wrap` is failing because there is no `wrap` column in `data_new`. You also still haven't provided a [mcve] so that others can reproduce and fix your error. –  May 26 '18 at 14:17
  • @dash2.thanks for your advice Sir. It fixed my issue. appreciate your help. – jay May 26 '18 at 19:07

0 Answers0