Reputation: 181
data<- c(100,101,102,103,104,99,98,97,94,93,103,90,104,105,110)
date<- Sys.Date()-15:1
file<- xts(data,date)
colnames(file)<- "CLOSE"
file$high<- cummax(file$CLOSE)
file$trade <- 0
file$trade[file$high*.95>=file$CLOSE] <- 1
file$trade[file$high*.90>=file$CLOSE] <- 2
file$trade[file$high*.85>=file$CLOSE] <- 3
file
CLOSE high trade
2013-07-06 100 100 0
2013-07-07 101 101 0
2013-07-08 102 102 0
2013-07-09 103 103 0
2013-07-10 104 104 0
2013-07-11 99 104 0
2013-07-12 98 104 1
2013-07-13 97 104 1
2013-07-14 94 104 1
2013-07-15 93 104 2
2013-07-16 103 104 0
2013-07-17 90 104 2
2013-07-18 104 104 0
2013-07-19 105 105 0
2013-07-20 110 110 0
I need to modify trade column, so after i get my first "1" then all elements would be zero until i get 2 and then all elements should be 0, till i get 3 and so on.
Upvotes: 3
Views: 99
Reputation: 557
I think, you could simply do:
> file$trade[duplicated(file$trade)] <- 0
Upvotes: 2
Reputation: 1013
You don't need a loop to do this. Indeed, you simply need to find the positions of the first "1", "2",.... Try the following codes.
rank.trade <- rank(file$trade, ties.method = "first")
marks <- cumsum(head(table(file$trade), -1)) + 1
black.list <- is.na(match(rank.trade, marks))
file$trade[black.list] <- 0
Upvotes: 2