1
votes

New to R. I created a new variable with dplyr::mutate() and I see the values in the df output when I run the code, but when I try to plot it with ggplot, I receive object not found error. What am I doing wrong? Thx.

Works as expected:

mutate(avg_inv = (inv_total / sr_count))

Error here:

# Plot avg invoice
p <- ggplot(df1, aes(x = Date_Group, y = avg_inv) ) +
  geom_bar(stat = "identity", position="dodge")
p

Error message:

Error in eval(expr, envir, enclos) : object 'avg_inv' not found

2
Did you save the mutated result to as df1? As in something like df1 = mutate(df1, avg_inv...). - aosmith
Thanks I'm using df so I changed df1 to df, but I receive the same error - Winston Snyder
It's possible to see the head of df ? - CClaire

2 Answers

2
votes

I think you might not be saving the result of mutate, so even though the results print to your console, it's not available for ggplot2. Try:

    df1 <- df %>% mutate(avg_inv = (inv_total / sr_count))
    p <- ggplot(df1, aes(x = Date_Group, y = avg_inv) ) +
                geom_bar(stat = "identity", position="dodge")
    p
1
votes

How about this; Here I'm computing the additional variable within the function call to ggplot. This saves me the hassle of a temporary variable to hold the temporary result and is error free too.

data("airquality")
library(ggplot2)
library(dplyr)
p<- ggplot(airquality %>%
             mutate(somevar=(Month/Day)), aes(x = somevar) ) +
  geom_histogram(position = "stack", stat = "bin", binwidth = 5)
print(p)