【发布时间】:2014-12-26 20:38:38
【问题描述】:
我正在尝试结合 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
有人知道怎么做吗?
【问题讨论】: