15

dplyr と stringr を組み合わせて、データフレーム内の複数のパターンを検出しようとしています。多数の異なる列をテストしたいので、dplyr を使用したいと考えています。

サンプルデータは次のとおりです。

test.data <- data.frame(item = c("Apple", "Bear", "Orange", "Pear", "Two Apples"))
fruit <- c("Apple", "Orange", "Pear")
test.data
        item
1      Apple
2       Bear
3     Orange
4       Pear
5 Two Apples

私が使いたいのは次のようなものです:

test.data <- test.data %>% mutate(is.fruit = str_detect(item, fruit))

そして受け取る

        item is.fruit
1      Apple        1
2       Bear        0
3     Orange        1
4       Pear        1
5 Two Apples        1

非常に単純なテストが機能します

> str_detect("Apple", fruit)
[1]  TRUE FALSE FALSE
> str_detect("Bear", fruit)
[1] FALSE FALSE FALSE

しかし、dplyr がなくても、データフレームの列に対してこれを機能させることはできません。

> test.data$is.fruit <- str_detect(test.data$item, fruit)
Error in check_pattern(pattern, string) : 
  Lengths of string and pattern not compatible

誰もこれを行う方法を知っていますか?

4

3 に答える 3

24

str_detect長さ 1 のパターンのみを受け入れます。paste(..., collapse = '|')またはを使用して1つの正規表現に変換しますany

sapply(test.data$item, function(x) any(sapply(fruit, str_detect, string = x)))
# Apple       Bear     Orange       Pear Two Apples
#  TRUE      FALSE       TRUE       TRUE       TRUE

str_detect(test.data$item, paste(fruit, collapse = '|'))
# [1]  TRUE FALSE  TRUE  TRUE  TRUE
于 2014-10-30T17:13:53.420 に答える