2015-12-10 52 views
3

我試圖做的是以下幾點: 使用grep()功能搜索模式(號碼列表,我把它叫做「toMatch」)在data.frame( 「新聞」)。所以,我想要它做的是在新聞中搜索這些數字並返回匹配(以「數字」,「相應新聞」的形式)。不幸的是,我至今只能得到相應新聞的清單。任何想法如何添加一個屬性與相應的數字從匹配到輸出? (在某種程度上創建一個鍵值對作爲輸出)如何添加屬性到grep()輸出

這裏我的代碼一個簡單的小例子:

News <- c ("AT000000STR2 is schwierig", "AT", "ATI", "AT000000STR1") 
toMatch <- c("AT000000STR1","AT000000STR2","DE000000STR1","DE000000STR2") 
matches <- unique (grep(paste(toMatch,collapse="|"),News, value=TRUE)) 
matches 

而且這裏的結果:

> matches 
[1] "AT000000STR2 is schwierig" "AT000000STR1" ` 

我想要有一個清單或更好的Excel文件,看起來像這樣:

AT000000STR2 "AT000000STR2 is schwierig" 
AT000000STR1 "AT000000STR1" 

幫助非常感謝。

+1

你希望每個 'toMatch' 的元素多獨特的比賽嗎?那麼輸出結果是什麼?你在這方面嘗試過什麼? – Heroka

+0

不在此示例中,但對於我的用例可能會有。我猜測會有數字與2個或更多新聞相對應。但是,我確實相信我已經通過獨特的功能處理這個問題了?你是這個意思嗎? – Kevin

+0

不,我的意思是,如果你的數據中有「AT000000STR1B」和「AT000000STR1C」。它們不是唯一的,並且都匹配「AT000000STR1」。 – Heroka

回答

3

像這樣的東西可能會有所幫助:

#name toMatch with its names 
names(toMatch) <- toMatch 

#create a list with the format you request 
myl <- 
lapply(toMatch, function(x) { 
    grep(x, News, value=TRUE) 
    }) 
#or in a more compact way as @BenBolker says in the comments below 
#myl <- lapply(toMatch, grep, x=News, value=TRUE) 

#remove the unmatched 
myl[lapply(myl,length)>0] 

輸出:

$AT000000STR1 
[1] "AT000000STR1" 

$AT000000STR2 
[1] "AT000000STR2 is schwierig" 
+0

我覺得'myl < - lapply(toMatch,grep,x = News,value = TRUE)'也可以工作(同樣的事情,但稍微緊湊) –

+0

謝謝@BenBolker。你說得對,它更緊湊。我養成了每次使用匿名函數的習慣:)。謝謝。 – LyzandeR

2

您當前的方法返回的唯一的比賽,但你有沒有將它們鏈接到相關「的方式toMatch 」。

這可能是您的一個開始:使用lapply我們爲toMatch的所有元素創建一個匹配列表,然後將這些匹配到toMatch。

matched <- lapply(toMatch, function(x){grep(x,News,value=T)}) 
#turn unfound matches to missings. You can remove these, but I don't like 
#generating implicit missings 
matched[sapply(matched,length)==0]<-NA 

res <- cbind(toMatch,matched) 
res 
    toMatch  matched      
[1,] "AT000000STR1" "AT000000STR1"    
[2,] "AT000000STR2" "AT000000STR2 is schwierig" 
[3,] "DE000000STR1" NA       
[4,] "DE000000STR2" NA   

寫入CSV是那麼簡單:

write.csv(res,"yourfile.csv")