0
votes

I would like to apply a function to a data.table to add a new column based on the evaluation of two columns from other data.tables.

Somehow I cannot get it to work:

require(data.table)
# Dummy data. In reality both tables are not identical
DT1 = data.table(
  a = c(-1,-1,1,1),
  b = c(-1.,1,-1,1)
)

DT2 = data.table(
  a = c(-1,-1,1,1),
  b = c(-1.,1,-1,1)
)

DT_RES = data.table (id = c(1:4))

check <- function(x1, x2) {
  if( (x1<0 && x2>0) || (x1>0 && x2<0)) {return(TRUE)}
  else {return(FALSE)}
}

#Try:
DT_RES[,"neg" := check(DT1[,1],DT2[,2])] # No error, but does not return the desired output

# Desired result:
data.table(id = c(1:4), neg=c(FALSE,TRUE,TRUE,FALSE))

Why is it not working?

1

1 Answers

1
votes

I think that you should not use the double && and ||, as they return TRUE only if both conditions are TRUE. These two functions work for me:

check <- function(x1, x2) {
  x <- ifelse((x1 < 0 & x2 > 0) | (x1 > 0 & x2 < 0), TRUE, FALSE)
  return(x)
}
check <- function(x1, x2) {
  if( (x1<0 & x2>0) | (x1>0 & x2<0)) {x <- TRUE}
  else {x <- FALSE}
  return(x)
}