【问题标题】:R: Add boolean column to a data.table based on return values of a function which evaluates two columns from different data.tableR:根据函数的返回值将布尔列添加到 data.table,该函数评估来自不同 data.table 的两列
【发布时间】:2021-05-16 02:54:32
【问题描述】:

我想对 data.table 应用一个函数,以根据来自其他 data.tables 的两列的评估来添加一个新列。

不知怎的,我无法让它工作:

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))

为什么它不起作用?

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    我认为您不应该使用双精度 &amp;&amp; 和 ||,因为它们仅在两个条件都为 TRUE 时才返回 TRUE。 这两个功能对我有用:

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 2020-07-29
      • 2015-07-08
      • 2021-09-13
      相关资源
      最近更新 更多