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
誰もこれを行う方法を知っていますか?