2015-12-10 51 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")