2009-10-29 94 views
5

我有一個包含2個字符列的數據框。我想找到一列中包含另一列的行,但是grepl很奇怪。有任何想法嗎?R中的列匹配字符串

> (df <- data.frame(letter=c('a','b'),food = c('apple','pear','bun','beets'))) 
    letter food 
1  a apple 
2  b pear 
3  a bun 
4  b beets 

> grepl(df$letter,df$food) 

[1] TRUE TRUE FALSE FALSE 

,但我想五六F T

感謝。

回答

5

感謝凱文的建議,使用申請,

> mapply(grepl,DF $信,DF $食品)

結果所需的輸出。

2

當我運行代碼,我得到一個警告:

Warning message: 
In grepl(df$letter, df$food) : 
    argument 'pattern' has length > 1 and only the first element will be used 

這是由?grepl確認下pattern

If a character vector of length 2 or more is supplied, 
the first element is used with a warning. 

所以grepl是找到一兩個蘋果和梨。這不能解決你的問題(應用或其變體之一?),但它解釋了你得到的輸出。

+0

謝謝。顯然這個警告在R 2.10.0版中是新的。 – novembera 2009-10-30 00:16:57

+0

我正在使用: R版本2.10.0已修補(2009-10-28 r50254) x86_64-apple-darwin9.8.0 – kmm 2009-10-30 00:19:00