Home > OS >  How to convert/transform column based on its mean value and reflect that on chart too in R?
How to convert/transform column based on its mean value and reflect that on chart too in R?

Time:05-01

I have the following dataframe and stacked area chart based on it

df <- data.frame (Year  = c("2010", "2010",  "2010", "2010", "2011","2011","2011","2011","2012","2012","2012","2012","2013","2013","2013","2013"),
                  Sales = c(100000000,200000000,50000000,500000000,400000000,200000000,400000000,145000000,100000000,456000000,345000000,321000000,100000000,200000000,250000000,400000000),
                 Category = c("A", "B",  "C", "D","A", "B",  "C", "D","A", "B",  "C", "D","A", "B",  "C", "D"))

df$Year <- as.integer(df$Year)

df %>% 
  ggplot(aes(x = Year, y = Sales, fill = Category))  
  geom_area()   scale_x_continuous(breaks=2010:2013)

Now I want to somehow code the following:

  1. If mean(df$Sales) > 1 000 000 Then df$Sales/1 000 000
  2. If mean(df$Sales) > 1 000 & <1 000 000 Then df$Sales/1 000
  3. Else do nothing

After I want to reflect that on ggplot y-axis:

  • if the 1st condition is met label y axis as "Sales in Trillion"
  • if the 2nd condition is met label y axis as "Sales in Billion" Else
  • label y axis as "Sales in Million"

CodePudding user response:

Wouldn't this if/else statement do the trick?

library(tidyverse)


y_label = "Sales in Million"
if(mean(df$Sales)>1000000){
  df$Sales2 = df$Sales/1000000
  y_label = "Sales in Billion"
} else if(mean(df$Sales)>1000){
  df$Sales2 = df$Sales/1000
  y_label = "Sales in Trillion"
}

df %>% 
  ggplot(aes(x = Year, y = Sales2, fill = Category))  
  geom_area()   scale_x_continuous(breaks=2010:2013)   
  ylab(y_label)

Created on 2022-04-30 by the reprex package (v2.0.1)

PS : 1 for a good question formatting with a sample dataset

  • Related