Search code examples
rif-statementapplysapply

Ifelse with multiple conditions in sapply function


I need to check each row in two columns for the two conditions in the dataframe (basically, I'm substracting each row in one pair of columns from each row in another pair of columns to get two certain values (one of which is time interval), see code). The expected result is another column with 1 if both conditions are satisfied and 0 otherwise.

I've tried:

sapply(trades1, function(x) x$indicator3 <- x %>% ifelse(indicator2 - indicator == -1 & difftime(date2, date, units = "min"== 1), 1, 0))

This gives me

 Error in ifelse(., indicator2 - indicator == -1 & difftime(date2, date,  : 
  unused argument (0) 

Solution

  • Assuming that trades1 is a data.frame`, we may need

    with(x, as.integer(((indicator2 - indicator) == -1) & 
         (difftime(date2, date, units = "min")== 1)))
    

    Make sure the difftime braces are closed