Reputation: 93
I have a data
x$buy_indicator <- c("HOLD","BUY","BUY","HOLD","HOLD","BUY","BUY","HOLD")
x$sell_indicator <- c("HOLD","HOLD","SELL","SELL","HOLD","SELL","SELL","HOLD")
I want my output data in such a way that when buy_indicator=BUY
and sell_indicator=SELL
, it should change into HOLD
in both the indicators
My R code
for(i in 1:nrow(x)){
if(x$Buy_indicator[i]=="BUY" & x$Sell_indicator[i]=="SELL") {x$Buy_indicator[i]=="HOLD" & x$Sell_indicator[i]=="HOLD"}}
Upvotes: 2
Views: 64
Reputation: 389235
We could create a logical vector to find rows where the values need to change
x[x$buy_indicator == "BUY" & x$sell_indicator == "SELL", ] <- "HOLD"
x
# buy_indicator sell_indicator
#1 HOLD HOLD
#2 BUY HOLD
#3 HOLD HOLD
#4 HOLD SELL
#5 HOLD HOLD
#6 HOLD HOLD
#7 HOLD HOLD
#8 HOLD HOLD
If you have other columns than buy_indicator
and sell_indicator
you can also subset columns
x[x$buy_indicator == "BUY" & x$sell_indicator == "SELL",
c("buy_indicator", "sell_indicator")] <- "HOLD"
data
x <- data.frame(
buy_indicator = c("HOLD","BUY","BUY","HOLD","HOLD","BUY","BUY","HOLD"),
sell_indicator = c("HOLD","HOLD","SELL","SELL","HOLD","SELL","SELL","HOLD"))
Upvotes: 4