mardi 23 avril 2019

Why does this ifelse return an "object not found" error?

I am attempting to build a ggplot but am running into an error here:

ggplot(nelMonthly) +
  geom_col(aes(month,
               overUnder,
           fill = ifelse(overUnder > 0, "red", "grey")), # THIS LINE THROWS THE ERROR
           colour = "black") +
  geom_text(aes(month, overUnder, label = overUnder),
                  vjust = ifelse(overUnder > 0, -0.25, 1),
                  size = 3,
                  colour = "black")

This returns:

Error in ifelse(overUnder > 0, -0.25, 1) : object 'overUnder' not found

However, if I explicitly specify the dataframe in the ifelse condition, it works correctly:

ggplot(nelMonthly) +
  geom_col(aes(month,
               overUnder,
           fill = ifelse(overUnder > 0, "red", "grey")),
           colour = "black") +
  geom_text(aes(month, overUnder, label = overUnder),
                  vjust = ifelse(nelMonthly$overUnder > 0, -0.25, 1),
                  size = 3,
                  colour = "black")

The problem I have with this is that it simply isn't how one should program because the data frame is passed inside ggplot(df).

Am I missing something here?

Why is this happening and how can I rectify it?

Aucun commentaire:

Enregistrer un commentaire