什么';s是SQL的R等价物';就像';说明%';陈述

什么';s是SQL的R等价物';就像';说明%';陈述,sql,r,Sql,R,我不知道该怎么问这个问题,但我想在几个字符串元素中搜索一个术语。下面是我的代码的样子(但错误): des是一个存储字符串的向量,如“摆动敲击”、“正在播放(运行)”、“正在播放(录制的输出)”等。我希望inplay存储的是与des向量对应的1s和0s向量,inplay中的1s表示des值中有“正在播放%”,否则为0s 我认为第三行是不正确的,因为它只返回一个0的向量,最后一个元素是1 提前谢谢 类似于regexpr > d <- c("Swinging Strike", "In pl

我不知道该怎么问这个问题,但我想在几个字符串元素中搜索一个术语。下面是我的代码的样子(但错误):

des是一个存储字符串的向量,如“摆动敲击”、“正在播放(运行)”、“正在播放(录制的输出)”等。我希望inplay存储的是与des向量对应的1s和0s向量,inplay中的1s表示des值中有“正在播放%”,否则为0s

我认为第三行是不正确的,因为它只返回一个0的向量,最后一个元素是1


提前谢谢

类似于
regexpr

> d <- c("Swinging Strike", "In play (run(s))", "In play (out(s) recorded)")
> regexpr('In play', d)
[1] -1  1  1
attr(,"match.length")
[1] -1  7  7
> 

类似于SQL的R只是R的普通索引语法

“LIKE”操作符通过将指定列中的字符串值与用户提供的模式相匹配,从表中选择数据行

> # create a data frame having a character column
> clrs = c("blue", "black", "brown", "beige", "berry", "bronze", "blue-green", "blueberry")
> dfx = data.frame(Velocity=sample(100, 8), Colors=clrs)
> dfx
            Velocity    Colors
        1       90       blue
        2       94      black
        3       71      brown
        4       36      beige
        5       75      berry
        6        2     bronze
        7       89    blue-green
        8       93    blueberry

> # create a pattern to use (the same as you would do when using the LIKE operator)
> ptn = '^be.*?'  # gets beige and berry but not blueberry
> # execute a pattern-matching function on your data to create an index vector
> ndx = grep(ptn, dfx$Colors, perl=T)
> # use this index vector to extract the rows you want from the data frome:
> selected_rows = dfx[ndx,]
> selected_rows
   Velocity Colors
     4       36  beige
     5       75  berry 
在SQL中,这将是:

SELECT * FROM dfx WHERE Colors LIKE ptn3

data.table
的语法通常是。该软件包包括%之类的
%,这是一个“调用regexpr的方便函数”。以下是从其帮助文件中获取的示例:

## Create the data.table:
DT = data.table(Name=c("Mary","George","Martha"), Salary=c(2,3,4))

## Subset the DT table where the Name column is like "Mar%":
DT[Name %like% "^Mar"]
##      Name Salary
## 1:   Mary      2
## 2: Martha      4

为什么要用
fnx
包装
grep()
?我最初想到的是一个函数,它将数据帧作为参数,而不仅仅是一维向量。在任何情况下,都可以通过编辑删除函数包装器。这是可行的,但假设我想在vector inplay中存储1(如果行号包含在ndx中),否则存储0(否则),其中vector inplay的长度是dfx的长度。我该怎么办?我在玩IF和ELSE语句,但我不能让它工作。提前谢谢!我想出来了。假设SL是存储“摆动打击”、“正在运行(s))”等的矩阵。ndx=grep(“^In play.*”,SL$des,perl=T)SL刚才看到了您的评论——所以您解决了上面的问题“我想存储什么…”。现在,我通常使用
%ilike%
,这是一个不区分大小写的版本
SELECT * FROM dfx WHERE Colors LIKE ptn3
## Create the data.table:
DT = data.table(Name=c("Mary","George","Martha"), Salary=c(2,3,4))

## Subset the DT table where the Name column is like "Mar%":
DT[Name %like% "^Mar"]
##      Name Salary
## 1:   Mary      2
## 2: Martha      4