小编典典

SQL的LIKE'description%'语句的R等效项是什么?

sql

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

inplay = vector(length=nrow(des))
for (ii in 1:nrow(des)) {
 if (des[ii] = 'In play%')
  inplay[ii] = 1
 else inplay[ii] = 0
}

des是一个向量,用于存储字符串,例如“SwingingStrike”,“进行中(运行)”,“进行中(记录的输出)”等。我要在存储中存储的是1s和0s对应于des向量的向量,其中ins为1表示ins中的des值具有“
in play%”,否则为0。

我相信第三行是不正确的,因为所有这一切都是返回最后一个元素中带有1的0s向量。

提前致谢!


阅读 175

收藏
2021-03-17

共1个答案

小编典典

SQL的LIKE的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
2021-03-17