-1

I hope i am able to explain myself well and am not asking a duplicate question.

I have a CSV file in which there is a column of sales. In that column i want to apply a logical function like if so that every row in that column is evaluated and returns the maximum value out of the selected rows. I am new to r done all my work in excel, so i am having difficulties.

Price   Price Events    Units      Sales      Sales/Event    Returned Price
2.31    1                737        1702       1702 
2.33    1                928        2162       2162          2.33
2.36    2                1660       3918       1959 
2.42    1                861        2084       2084

IN the column Sales per event i want to apply a function in which if(and(Sales_Per_Event$2>Sales_Per_Event$1 , Sales_Per_Event$2>Sales_Per_Event$3 , Price$2 , ""))

1 Answers1

0

I believe I finally understood your question. If not just say so.
First, the data.

dat <-
structure(list(Price = c(2.31, 2.33, 2.36, 2.42), Price_Events = c(1L, 
1L, 2L, 1L), Units = c(737L, 928L, 1660L, 861L), Sales = c(1702L, 
2162L, 3918L, 2084L), Sales_per_Event = c(1702L, 2162L, 1959L, 
2084L)), .Names = c("Price", "Price_Events", "Units", "Sales", 
"Sales_per_Event"), class = "data.frame", row.names = c(NA, -4L
))

Now, the code.

#
# Input   x - Sales_per_Event
#         y - Price
# Returns z - Returned_Price
#
abhik <- function(x, y){
    n <- length(x)
    z <- numeric(n)
    z[1] <- NA
    z[n] <- NA
    for(i in seq_along(x)[-c(1, n)]){
        if(x[i] > x[i - 1] && x[i] > x[i + 1])
            z[i] <- y[i]
        else
            z[i] <- NA
    }
    z
}

abhik(dat$Sales_per_Event, dat$Price)
#[1]   NA 2.33   NA   NA

dat$Returned_Price <- abhik(dat$Sales_per_Event, dat$Price)
dat

Note that I have opted for NA instead of blank character values because blanks would transform your entire column into character or, worse, factors.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66