如何在R的需求曲线上找到使利润最大化的最佳点?

问题描述

R相对较新,所以请多多包涵-我的数据集与一种产品有关。我有一个针对此产品的每单位价格点的列表(价格取决于销售人员的决定),以及数量(在每个价格点购买的单位数)的列表,以及每笔交易的相应利润。>

我绘制了一条需求曲线,其中Y轴为数量,X轴为单价。我还绘制了一个线性回归模型,该模型给出了系数和截距,并允许我绘制表示该关系的斜线。代码如下:

#Model

testlm <- lm(Dataset$Quantity Sold~Dataset$Unit Price)

#Plot

plot(Dataset$Unit Price,Dataset$Quantity Sold,xlab = "Unit Price",ylab = "Quantity",pch=20,ylim=c(0,40))

#abline

abline(a=11.38,b=-0.24,col="blue",lwd=2)

##这是我要输入两条线越过最佳点的地方

abline(v=OptimalUnitPrice,lty=4,col = "red",lwd=2)
abline(h=OptimalQty,lwd=2)`

我试图弄清楚如何找到OptimalUnitPrice和OptimalQty的值-我试图找到一个与Excel的Solver相似的功能-使我能够找到将数量作为因素的最优价格,并使利润最大化。我相信我必须将利润叠加到关系中和/或以某种方式绘制图表,但是我不知道该怎么做。

有人可以帮忙吗?谢谢!

解决方法

希望此示例可以为您提供帮助。

library(data.table)
library(ggplot2)
library(magrittr)

# linear function 
linear <- function(p,alpha,beta) {
  alpha*p + beta
}

# Synthetic data
p <- seq(60,200)
d <- linear(p,alpha = -1.5,beta = 300) + rnorm(sd = 5,length(p))
c <- 88
profit <- d*(p-c)

# Fit of the demand model
lm_model <- lm(d~p)
profit_fitted <-  lm_model$fitted.values*(p - c)

# Pricing Optimization
alpha <- lm_model$coefficients[2]
beta <- lm_model$coefficients[1]
p_max_profit <- (alpha*c - beta)/(2*alpha)

# Plots: Prices X Demand 
df_linear <- data.table('Prices' = p,'Demand' = d,'profit_fitted' = profit_fitted,'Profit' = profit)

ggplot(df_linear) + aes(x = Prices,y = Demand) +
  geom_point() + geom_smooth(method = lm)

# Plots: Prices X Profit
ggplot(df_linear) + 
  aes(x = Prices,y = Profit) +
  geom_point() + geom_vline(xintercept = p_max_profit,lty = 2) +
  geom_line(data = df_linear,aes(x = Prices,y = profit_fitted),color = 'blue')