Data.table: 将 PostgreSQL 的 %ilike% 包含到 data.table 中

创建于 2017-12-13  ·  3评论  ·  资料来源: Rdatatable/data.table

我非常喜欢 data.table 中的%like%运算符,因为我习惯了 SQL 查询。 在 PostgreSQL 中还有ILIKE选项,其中 __i__ 代表 case-__insensitive__。

您如何看待将%ilike%包含到 data.table 中?

要将其包含到 data.table 中,我将在 ilike.R 中创建一个运算符%ilike% ,基于 like.R 将ignore.case = TRUE添加到grep()调用中,如下所示:

ilike <- function(vector, pattern)
{
  # Intended for use with a data.table 'where'
  # Don't use * or % like SQL's like.  Uses regexpr syntax - more powerful.
  if (is.factor(vector)) {
    as.integer(vector) %in% grep(pattern,levels(vector), ignore.case = TRUE)
  } else {
    # most usually character, but integer and numerics will be silently coerced by grepl
    grepl(pattern,vector, ignore.case = TRUE)
  }
  # returns 'logical' so can be combined with other where clauses.
}

"%ilike%" = ilike

可重现的例子:

require(data.table)
cars = data.table(cars = rownames(mtcars), mtcars)

cars[ cars %like% 'fiat' ] # no case-insensitive search possible
cars[ grep('fiat', cars, ignore.case = TRUE) ] # using comparably long grep
cars[ cars %ilike% 'fiat' ] # the new %ilike%
beginner-task

最有用的评论

确实也有效,不知道这样的正则表达式。 不过%ilike%对我来说似乎更直观。 也许是因为我了解 PostgreSQL。 总的来说,无论如何,这是一个编码风格的问题。

所有3条评论

您可以改用(?i)标签:

cars[cars %like% '(?i)fiat']

确实也有效,不知道这样的正则表达式。 不过%ilike%对我来说似乎更直观。 也许是因为我了解 PostgreSQL。 总的来说,无论如何,这是一个编码风格的问题。

@andreasLD再次感谢您的提出。 您可能已经看到了,因为您也在那里发表了评论,但要记录在案,这已在 #3333 和 #3552 中关闭

此页面是否有帮助?
0 / 5 - 0 等级