0

I want to have 2 conditions in my if statement but somehow it doesn't work. Can anyone maybe help me?

this is my data set I want to check if the prediction (Pred1) is true. It is true when Pred1 = "bullish" & Price < RealPrice

My code:

df$result <- ifelse(grepl("bullish", df$Pred1, fixed = TRUE) && df$Price < df$RealPrice, "true",ifelse(grepl("bearish", df$Pred1, fixed = TRUE) && df$Price > df$RealPrice, "true"), "false")

enter image description here

Sotos
  • 51,121
  • 6
  • 32
  • 66
theG
  • 1
  • 1
  • 1
    You can only use 1 "&" instead of 2. Also, your second ifelse statement has no result for the FALSE condition. – Yacine Hajji Jan 13 '22 at 12:08
  • `ifelse((grepl("bullish", df$Pred1, fixed = TRUE) & df$Price < df$RealPrice) | (grepl("bearish", df$Pred1, fixed = TRUE) & df$Price > df$RealPrice), "true", "false")`, or more easy to read, `with(df, ifelse((grepl("bullish", Pred1, fixed = TRUE) & Price < RealPrice) | (grepl("bearish", Pred1, fixed = TRUE) & Price > RealPrice), "true", "false"))` – r2evans Jan 13 '22 at 12:27
  • FYI, @theG, when working with data in this way, I much prefer using "real" boolean-class objects, so instead of `"true"`/`"false"` (or their upper-case versions), I **much** prefer real logical objects `TRUE` and `FALSE`. One could easily change the above to be `ifelse((a&b)|(d&e),TRUE,FALSE)`, or one could remove the `ifelse` and just go with `(a&b)|(d&e)`, which will return the boolean objects. Hope this helps. – r2evans Jan 14 '22 at 12:09

1 Answers1

0
This should do what you're looking for:

        
    df=data.frame(Pred1 = c("bullish","ABCDE", "EDFGI", "bullish"), 
                      Price = c(100,200,300,400),
                      RealPrice = c(200,100,300,500))
        
        
    df = df %>% 
    mutate(result = case_when(Pred1 == "bullish" & Price < RealPrice ~ "TRUE",
                              Pred1 != "bullish" & Price >=RealPrice ~ "FALSE"))
                           
                          
thehand0
  • 1,123
  • 4
  • 14