我有这样的数据集
df <- data.frame(ID = c(334, 111, 324, 234),
Name = c("Tom", "Mike", "John", "Tim"),
Score = c(2, 9, 3, 5))
通过使用dplyr包,如何从3开始排除ID。
答案 0 :(得分:2)
您可以使用dplyr
:
library(dplyr)
df %>%
filter(grepl("^[^3]", ID))
<强>结果:强>
ID Name Score
1 111 Mike 9
2 234 Tim 5
数据:强>
df = data.frame(ID = c(334, 111, 324, 234),
Name = c("Tom", "Mike", "John", "Tim"),
Score = c(2, 9, 3, 5))
答案 1 :(得分:1)
library(dplyr)
library(microbenchmark)
N <- 1e6
要测试的功能:
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, ]
使用原始OP数据:
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
使用更大的OP数据:
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