我必须过滤一个数据帧使用作为标准的那些行,其中包含字符串RTB。

我正在使用dplyr。

d.del <- df %>%
  group_by(TrackingPixel) %>%
  summarise(MonthDelivery = as.integer(sum(Revenue))) %>%
  arrange(desc(MonthDelivery))

我知道我可以在dplyr中使用函数过滤器,但我不知道如何告诉它检查字符串的内容。

特别是,我想检查TrackingPixel列中的内容。如果字符串包含标签RTB,我想从结果中删除行。


当前回答

根据Akruns的建议,还有一个进一步的选择——用rowsum和子集创建一个逻辑向量。只有以r为底数时,这是特别有用和优雅的,当列包含我们正在寻找的值时。(或者你可以像下面这样用简单的条件语句创建一个二维数组:df1 == "no_data")

## this is very easy when the expected value is EXACTLY the string
df1 <- structure(list(time = c("1:00", "2:00", "no_data", "3:00"), speed = c("30", "no_data", "no_data", "50"), wheels = c("no_data", "18", "no_data", "18")), .Names = c("time", "speed", "wheels"), class = "data.frame", row.names = c(NA, -4L))
df1[rowSums(df1 == "no_data") == 0, , drop = FALSE]
#>   time speed wheels
#> 4 3:00    50     18

## it's a bit more verbose when the expected value just CONTAINS the string
mtcars$type <- rownames(mtcars)
mtcars[rowSums(apply(mtcars, 2, \(x) grepl('Toyota|Mazda', x))) > 0, , drop = FALSE] |> head()
#>                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#> Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
#>                          type
#> Mazda RX4           Mazda RX4
#> Mazda RX4 Wag   Mazda RX4 Wag
#> Toyota Corolla Toyota Corolla
#> Toyota Corona   Toyota Corona

其他回答

编辑更新过滤器(if_all/if_any)语法(dplyr vs. 1.0.10),以前使用across(现已弃用),甚至在filter_all或filter_any(已取代)之前使用。

下面是另一个dplyr解决方案,使用过滤器(if_all/if_any)。这样做的好处是可以轻松扩展到多个列。下面展示了如何在任何列中过滤具有给定字符串的行,以菱形为例,寻找字符串“V”。

删除任何列满足条件的行

library(dplyr)

## with if_any
ggplot2::diamonds %>%
  ## NB ! needs to come before if_any
  filter(!if_any(everything(), ~ grepl('V', .))) %>%
  head()
#> # A tibble: 6 × 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

## or with if_all
ggplot2::diamonds %>%
  filter(if_all(everything(), ~ !grepl('V', .))) %>%
  head()
#> # A tibble: 6 × 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

筛选任意列满足条件的行

## The new syntax makes it also easy to positively filter rows 
## where one columns fulfils a condition
ggplot2::diamonds %>%
  filter(if_any(everything(), ~ grepl('V',.))) %>%
  head()
#> # A tibble: 6 × 10
#>   carat cut       color clarity depth table price     x     y     z
#>   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
#> 2  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
#> 3  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
#> 4  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
#> 5  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
#> 6  0.22 Fair      E     VS2      65.1    61   337  3.87  3.78  2.49

解决方案

可以使用tidyverse包中包含的stringr包的str_detect。str_detect返回True或False关于指定的向量是否包含特定的字符串。可以使用这个布尔值进行筛选。关于stringr包的详细信息请参见stringr简介。

library(tidyverse)
# ─ Attaching packages ──────────────────── tidyverse 1.2.1 ─
# ✔ ggplot2 2.2.1     ✔ purrr   0.2.4
# ✔ tibble  1.4.2     ✔ dplyr   0.7.4
# ✔ tidyr   0.7.2     ✔ stringr 1.2.0
# ✔ readr   1.1.1     ✔ forcats 0.3.0
# ─ Conflicts ───────────────────── tidyverse_conflicts() ─
# ✖ dplyr::filter() masks stats::filter()
# ✖ dplyr::lag()    masks stats::lag()

mtcars$type <- rownames(mtcars)
mtcars %>%
  filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
# 1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
# 2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
# 4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

斯金格的优点

我们应该使用stringr::str_detect()而不是base::grepl()。这是因为有以下原因。

stringr包提供的函数以前缀str_开头,这使得代码更容易阅读。 stringr包的函数的第一个参数总是data.frame(或value),然后是形参。(谢谢Paolo)

object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"

基准

基准测试结果如下。对于大数据帧,str_detect更快。

library(rbenchmark)
library(tidyverse)

# The data. Data expo 09. ASA Statistics Computing and Graphics 
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728      29

benchmark(
  "str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
  "grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
  replications = 10,
  columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2      grepl           10  16.480    1.513    16.195    0.248
# 1 str_detect           10  10.891    1.000     9.594    1.281

根据Akruns的建议,还有一个进一步的选择——用rowsum和子集创建一个逻辑向量。只有以r为底数时,这是特别有用和优雅的,当列包含我们正在寻找的值时。(或者你可以像下面这样用简单的条件语句创建一个二维数组:df1 == "no_data")

## this is very easy when the expected value is EXACTLY the string
df1 <- structure(list(time = c("1:00", "2:00", "no_data", "3:00"), speed = c("30", "no_data", "no_data", "50"), wheels = c("no_data", "18", "no_data", "18")), .Names = c("time", "speed", "wheels"), class = "data.frame", row.names = c(NA, -4L))
df1[rowSums(df1 == "no_data") == 0, , drop = FALSE]
#>   time speed wheels
#> 4 3:00    50     18

## it's a bit more verbose when the expected value just CONTAINS the string
mtcars$type <- rownames(mtcars)
mtcars[rowSums(apply(mtcars, 2, \(x) grepl('Toyota|Mazda', x))) > 0, , drop = FALSE] |> head()
#>                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#> Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
#>                          type
#> Mazda RX4           Mazda RX4
#> Mazda RX4 Wag   Mazda RX4 Wag
#> Toyota Corolla Toyota Corolla
#> Toyota Corona   Toyota Corona

这个问题的答案已经由@latemail在上面的评论中发布了。你可以对filter的第二个参数和后面的参数使用正则表达式,如下所示:

dplyr::filter(df, !grepl("RTB",TrackingPixel))

由于您没有提供原始数据,我将使用mtcars数据集添加一个简单的示例。假设你只对马自达或丰田生产的汽车感兴趣。

mtcars$type <- rownames(mtcars)
dplyr::filter(mtcars, grepl('Toyota|Mazda', type))

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

如果你想反过来做,即排除丰田和马自达汽车,过滤器命令看起来像这样:

dplyr::filter(mtcars, !grepl('Toyota|Mazda', type))

这个答案与其他答案相似,但使用首选的stringr::str_detect和dplyr rownames_to_column。

library(tidyverse)

mtcars %>% 
  rownames_to_column("type") %>% 
  filter(stringr::str_detect(type, 'Toyota|Mazda') )

#>             type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1      Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> 2  Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> 3 Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#> 4  Toyota Corona 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1

由reprex包于2018-06-26创建(v0.2.0)。