How can I find the optimal price for each time t in R?

132 Views Asked by At

I have the price range price <- c(2.5,2.6,2.7,2.8) and my dataset have several time t. For each time t, I have a corresponding cost c and demand quantity d. I need to find the optimal price for each time t to maximise my required profit function (p-c)*d. How can I achieve that?

The sample of mydata looks like this, I have 74 observations in total:

t c d
1 0.8 20
2 0.44 34
3 0.54 56
4 0.67 78
5 0.65 35

Here is my code but it reports error, can anybody help me to fix it? Much thanks!

max <-data.frame()

for (i in mydata$t) {
  for (p in price) {
    profit <- ((p-mydata$c)*mydata$d)
    max <- max %>% bind_rows(data.frame(time=mydata$t,
                                        price=p,
                                        cost=mydata$c,
                                        profit = profit

))
  }
}
  maxvalue <- max %>% group_by(time) %>% max(profit)
2

There are 2 best solutions below

1
On

Since you did not provide a piece of your data which I could use, this is a bit of a guess, but the idea would be:

dat <- as.data.table(mydata)
# Iterate through each value of t and get the price for which (p-c)*d is the highest
result <- dat[, p[which.max((p-c)*d))], t] 
2
On

Ok! I did not realize you kept the price outside your table. Then try adding all possibilities to the table first this:

dat <- data.table(t= 1:5,
                  c= c(0.8,0.44,0.54,0.67,0.65),
                  d= c(20,34,56,78,35))
# Add all possible prices as an extra column (named p)
# Note that all lines will be repeated accordingly
dat <- dat[, .(p= c(2.5,2.6,2.7,2.8)), (dat)]
# Iterate through each value of t and get the price for which (p-c)*d is the highest
result <- dat[, .(best_price= p[which.max((p-c)*d)]), t]