我有数据
x$buy_indicator <- c("HOLD","BUY","BUY","HOLD","HOLD","BUY","BUY","HOLD")
x$sell_indicator <- c("HOLD","HOLD","SELL","SELL","HOLD","SELL","SELL","HOLD")
我希望我的输出数据以这样的方式显示,当buy_indicator=BUY
和sell_indicator=SELL
时,它们在两个指标中都应变为HOLD
我的R代码
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"}}
答案 0 :(得分:4)
我们可以创建一个逻辑矢量来查找需要更改值的行
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
如果您有buy_indicator
和sell_indicator
以外的其他列,则还可以将这些列作为子集
x[x$buy_indicator == "BUY" & x$sell_indicator == "SELL",
c("buy_indicator", "sell_indicator")] <- "HOLD"
数据
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"))