joerna
joerna

Reputation: 435

dplyr excluding the row start with certain number

I have data set like this

df <- data.frame(ID    = c(334, 111, 324, 234), 
                 Name  = c("Tom", "Mike", "John", "Tim"), 
                 Score = c(2, 9, 3, 5))

By using dplyr package, how can I exclude ID starting with 3.

Upvotes: 1

Views: 353

Answers (2)

acylam
acylam

Reputation: 18701

This is how you can do it using dplyr:

library(dplyr)
df %>%
  filter(grepl("^[^3]", ID))

Result:

   ID Name Score
1 111 Mike     9
2 234  Tim     5

Data:

df = data.frame(ID = c(334, 111, 324, 234), 
                Name = c("Tom", "Mike", "John", "Tim"), 
                Score = c(2, 9, 3, 5))

Upvotes: 2

pogibas
pogibas

Reputation: 28379

library(dplyr)
library(microbenchmark)
N <- 1e6

Functions to test:

f_grep  <- function() df[grep("^3", df$ID, invert = TRUE), ]
f_grepl <- function() df[!grepl("^3", df$ID), ]
f_modul <- function() df[df$ID %/% 300 != 1, ]
f_sWith <- function() df[startsWith(as.character(df$ID), "3"), ]
f_subSt <- function() df[substr(df$ID, 1, 1) != 3, ]

Using original OPs data:

df <- data.frame(ID    = c(334, 111, 324, 234), 
                 Name  = c("Tom", "Mike", "John", "Tim"), 
                 Score = c(2, 9, 3, 5))

microbenchmark(f_grep(), f_grepl(), f_modul(), f_sWith(), f_subSt())

Unit: microseconds
      expr    min      lq      mean  median      uq       max neval
  f_grep() 42.207 47.0645  65.51158 58.0910 62.2905   865.607   100
 f_grepl() 35.762 40.5785  59.13411 49.6425 54.4015  1023.742   100
 f_modul() 27.659 32.4575 154.65156 41.5485 44.1945 10969.091   100
 f_sWith() 30.866 35.0830  93.27367 44.0320 47.3740  3642.091   100
 f_subSt() 33.470 37.8465  57.94782 47.1935 49.5860   991.518   100

Using larger OPs data:

df <- data.frame(ID    = sample(df$ID, N, replace = TRUE),
                 Name  = sample(df$Name, N, replace = TRUE),
                 Score = sample(df$Score, N, replace = TRUE))

microbenchmark(f_grep(), f_grepl(), f_modul(), f_sWith(), f_subSt())

Unit: milliseconds
      expr       min        lq      mean    median        uq       max neval
  f_grep() 472.19564 479.15768 492.12995 495.77323 503.16749 538.67349   100
 f_grepl() 478.68982 483.25584 496.40382 501.86222 507.34989 535.04327   100
 f_modul()  29.78637  30.74446  41.82639  32.61941  53.58474  62.51763   100
 f_sWith() 386.47298 388.99461 401.46679 398.01549 412.25743 435.97195   100
 f_subSt() 423.53511 426.11061 438.80629 442.81014 449.26856 471.70923   100

Upvotes: 1

Related Questions