Search code examples
rggplot2syntax-errornumeric

Non-numeric argument error to binary operation in R, needs explanation


This is a continuation of (how to modify axis labels ggplot in R). The code supplied works beautifully. The data is created manually. So I transferred that a larger dataset and am now getting the following error.

   Error in aes(y = AnnualDifference, x = (reorder(Seriesttls, AnnualDifference))) +  :
   non-numeric argument to binary operator

This is the code being used

   jobgrowthbyindustry<-ggplot(data=nvces2, aes(y=AnnualDifference,x= 
   (reorder(Seriesttls,AnnualDifference)))+geom_col(color="blue")
   +coord_flip()+labs(x=NULL)+ggtitle("Nevada Nonfarm Job Growth by Industry"))+
   theme(plot.title.position = "plot",
   plot.title = element_text(hjust =0.5))

If this is of any assistance, the AnnualDifference item is created using the following code

  nvces<- nvces%>%
  group_by(adjusted,areaname,seriescode)%>%
  mutate(PreviousYear=lag(ravg,12), 
     PreviousMonth=lag(ravg),
     AnnualDifference=ravg-PreviousYear,
     MonthlyDifference=ravg-PreviousMonth,
     MonthlyGrowthRate=MonthlyDifference/PreviousMonth,
     PercentGrowthRate=AnnualDifference/PreviousYear)%>%
  ungroup()

Where my confusion comes is that the data types for the items involved in the chart are the same. Seriesttls is character and AnnualDifference (or A in the previous question) is numeric. Yet in the first I get no errors and in the second one, I do. Any thoughts on why this is?


Solution

  • In my experience, this error typically pops up if I got one of the parentheses wrong and am trying to add something within the call to ggplot. Your formatting makes this difficult to see, so let's look at this more nicely formatted:

       jobgrowthbyindustry <- 
          ggplot(data=nvces2, 
                 aes(y = AnnualDifference, 
                     x = (reorder(Seriesttls,AnnualDifference))   
                     )
                 + geom_col(color="blue")
                 + coord_flip()
                 + labs(x=NULL)
                 + ggtitle("Nevada Nonfarm Job Growth by Industry")
                 ) + theme(plot.title.position = "plot",
                           plot.title = element_text(hjust =0.5)
                 )
    

    One of the parentheses is misplaced.

    It should be:

       jobgrowthbyindustry <- 
          ggplot(data=nvces2, 
                 aes(y = AnnualDifference, 
                     x = (reorder(Seriesttls,AnnualDifference))   
                     )
                 ) +
         geom_col(color="blue") +
         coord_flip() +
         labs(x=NULL) +
         ggtitle("Nevada Nonfarm Job Growth by Industry") +
         theme(plot.title.position = "plot",
               plot.title = element_text(hjust =0.5)
               )
    

    And you can also remove the redundant () around the call to reorder.

    If this is not resolving your issue, please do provide some data so that we can reproduce the error.