2010-08-22 44 views
15

不知道怎麼問這個,但是,我想在幾個字符串元素內搜索一個詞。這裏是我的代碼是什麼樣子的(但錯誤):什麼是SQL的LIKE'description%'語句的R等價物?

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

德是存儲字符串,如「搖擺罷工」,「比賽中(運行(S))」,「比賽(出(一個向量s )記錄)等等。我想要存儲的是與des矢量對應的1s和0s矢量,其中inplay中的1表示des值具有「正在播放%」,否則爲0。

我相信第三行是不正確的,因爲所有這一切都是在最後一個元素中返回一個0的向量和1。

提前致謝!

+0

你想'startsWith'? – 2010-08-22 02:21:33

回答

14

將R模擬SQL就像是剛剛的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 
+0

爲什麼你用'fnx'封裝'grep()'? – Vince 2010-08-22 03:54:49

+0

我原先想到的是一個函數,它把數據框作爲參數,而不僅僅是一維矢量。無論如何,編輯刪除函數包裝。 – doug 2010-08-22 04:29:01

+0

這是有效的,但假設我想在向量中存儲一個1,如果行號包含在ndx中,則爲0;否則,向量inplay的長度是dfx的長度。我如何去做這件事? 我正在玩IF和ELSE語句,但我沒有得到這個工作。提前致謝! – 2010-08-22 11:39:59

2

類似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 
> 

grep

> grep('In play', d) 
[1] 2 3 
> 
16

data.tablepackage的語法通常是similar to SQL。該軟件包包括%like%,這是一個「調用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 
相關問題