Search code examples
rmeanquadratic

Calculate mean values in a quadratic curve


Here's a sample data

 sales <- function(price) { 100 - 0.5 * price }
 x <- 50:150
 x1 <- sales(x)
 revenue <- function(price) { price * sales(price) }
 y<- revenue(x)

 dat <- as.data.frame(cbind(y,x))
 plot(dat$y ~ dat$x)

enter image description here

I want to calculate 2 means of y:

(1) Mean 1: mean of y starting the first value of x till y reaches the maximum value (in the middle).

(2) Mean 2: mean of y from the maximum value till it reaches the minimum value at the last value of x.

I thought I will sort out the data first according to increasing x-values

dat1 <- dat[order(dat$x),]

But I am stuck here. I am not sure how do I calculate the two means from here?


Solution

  • You can use split function:

    n <- 2
    dfchunk <- split(dat1, factor(sort(rank(row.names(dat1))%%n)))
    

    This will give you a list of 2.

    Then you can get the mean for each of them:

    avgYFirstHalf  <- mean(dfchunk$`0`$y)
    avgYSecondHalf <- mean(dfchunk$`1`$y)
    
    > avgYFirstHalf
    # 4570.75
    > avgYSecondHalf 
    # 4579.167