0

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 Answers2

0

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] 
V. Lou
  • 159
  • 5
  • Hi Lou, I've updated my post and you can see the data there. I tried your suggested code, but I got the error: The items in the 'by' or 'keyby' list are length(s) (1). Each must be length 74; the same length as there are rows in x (after subsetting if i is provided). – Tiffany Guo Mar 12 '22 at 17:20
0

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]
V. Lou
  • 159
  • 5
  • Hi Luo, all codes work fine except the last line, I still get the error: The items in the 'by' or 'keyby' list are length(s) (74). Each must be length 1480; the same length as there are rows in x (after subsetting if i is provided). Thank you soo much! – Tiffany Guo Mar 12 '22 at 19:34
  • Hi, sorry but I did not run my code to test it before sending, there was a typo. I updated my answer, and running this in R works for me. Make sure that the name of your variables are consistent throughout the code – V. Lou Mar 12 '22 at 21:08