我有一个简单的数据框,如下所示:
x <- c("aa", "aa", "aa", "bb", "cc", "cc", "cc")
y <- c(101, 102, 113, 201, 202, 344, 407)
df = data.frame(x, y)
x y
1 aa 101
2 aa 102
3 aa 113
4 bb 201
5 cc 202
6 cc 344
7 cc 407
Run Code Online (Sandbox Code Playgroud)
我想使用dplyr :: filter()和RegEx来过滤掉y以数字开头的所有观察结果1
我想象代码看起来像这样:
df %>%
filter(y != grep("^1"))
Run Code Online (Sandbox Code Playgroud)
但我得到了一个 Error in grep("^1") : argument "x" is missing, with no default
tal*_*lat 35
你需要仔细检查单证的grepl和filter.
对于grep/ grepl您还必须提供要检入的向量(在本例中为y)并filter采用逻辑向量(即您需要使用grepl).如果要提供索引向量(from grep),可以使用slice.
df %>% filter(!grepl("^1", y))
Run Code Online (Sandbox Code Playgroud)
或者使用源自以下的索引grep:
df %>% slice(grep("^1", y, invert = TRUE))
Run Code Online (Sandbox Code Playgroud)
但你也可以使用,substr因为你只对第一个字符感兴趣:
df %>% filter(substr(y, 1, 1) != 1)
Run Code Online (Sandbox Code Playgroud)
随着组合dplyr以及stringr(在tidyverse内住宿),你可以这样做:
df %>% filter(!str_detect(y, "^1"))
Run Code Online (Sandbox Code Playgroud)
之所以有效,是因为str_detect返回逻辑向量。
| 归档时间: |
|
| 查看次数: |
19991 次 |
| 最近记录: |