mercredi 2 décembre 2015

ifelse conditional formatting in r

I'm relatively new to R. I have a data frame, in which I would like to create a variable that does conditional formatting. Below is a sample of the data that I am working with.

cycle <- c("M", "O", "O", "O", "O", "M", "O")
irm <- c("200901", "200902", "200903", "200904", "200905", "200906", "200907")
itemcode <- c("611420B004A01", "611420B004A01", "611420B004A01", "611420B004A01", "611420B004A01", "611420B004A01", "611420B004A01")
price <- c(19.00, NA, NA, NA, NA, NA, NA)
dlq <- c(0, 0, 0, 0, 0, 1, 1)
df <- data.frame(itemcode, irm, price, cycle, dlq)

The dlq variable is conditional on the value of the cycle variable. I would like to define it such that, for every unique value of itemcode (I have 75,000 of them) it is equal to 1 if price is empty during a month where cycle is equal to M or if cycle is equal to O and the most recent month where cycle = M price was NA. For example, dlq = 1 where irm = 200907 because cycle = M in 200906 and price was equal to NA and it's also empty where irm = 200907. I've tried using lead and lag variables, but the number of months between an M and an O is not constant. So, I want dlq = 1 if and only if cycle = "O" and price = NA in the last month where cycle = M. Is there a way to do this with ifelse or some other conditions? Any advice/help would be much appreciated. Thanks so much.

Aucun commentaire:

Enregistrer un commentaire