如何根据其平均值 convert/transform 列并将其反映在 R 中的图表上?
How to convert/transform column based on its mean value and reflect that on chart too in R?
我有以下数据框和基于它的堆积面积图
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)
现在我想以某种方式编写以下代码:
- 如果
mean(df$Sales)
> 1 000 000 那么 df$Sales/1 000 000
- 如果
mean(df$Sales)
> 1 000 & <1 000 000 那么 df$Sales/1 000
- 否则什么也不做
在我想在 ggplot y 轴上反映之后:
- 如果满足第一个条件,则将 y 轴标记为“万亿销售额”
- 如果满足第二个条件,则将 y 轴标记为“十亿销售额”,否则
- 将 y 轴标记为“百万销售额”
这个 if/else 语句不能解决问题吗?
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)
由 reprex package (v2.0.1)
于 2022-04-30 创建
PS :+1 用于使用示例数据集格式化问题
我有以下数据框和基于它的堆积面积图
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)
现在我想以某种方式编写以下代码:
- 如果
mean(df$Sales)
> 1 000 000 那么df$Sales/1 000 000
- 如果
mean(df$Sales)
> 1 000 & <1 000 000 那么df$Sales/1 000
- 否则什么也不做
在我想在 ggplot y 轴上反映之后:
- 如果满足第一个条件,则将 y 轴标记为“万亿销售额”
- 如果满足第二个条件,则将 y 轴标记为“十亿销售额”,否则
- 将 y 轴标记为“百万销售额”
这个 if/else 语句不能解决问题吗?
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)
由 reprex package (v2.0.1)
于 2022-04-30 创建PS :+1 用于使用示例数据集格式化问题