[英]r - retain rows when certain condition is met in column
df <- data.frame(a = c(1:5), b=c("df_1_1","df_1_2","df_2_3","df_1_1","df_2_4"))
只有當 b 列中最左邊的 5 個字符串是“_1_1”時,我才想保留行。 所以在這種情況下,只會保留第 1 行和第 4 行。
謝謝
我們可以使用grepl
來匹配部分字符串,即字符串末尾( $
)的_1_1
以subset
base R
中的那些行
subset(df, grepl('_1_1$', b))
# a b
#1 1 df_1_1
#4 4 df_1_1
另一個基本 R 選項使用subset
+ endsWith
> subset(df,endsWith(b,"_1_1"))
a b
1 1 df_1_1
4 4 df_1_1
首先,應僅以交互方式使用subset
。 當您想要子集時,使用標准子集: df$b
和df[match_row,]
。
通常,當您想要 grep 基礎 R 中的某個字符串時,您使用base::grep
。 如果您不需要正則表達式,您可以使用fixed=TRUE
來加快 function。
在這里,我將比較 @akrun grepl
、 grep
、 @ThomasIsCoding 的endsWith
(很好的發現!)和stringr
庫中的解決方案。
df <- data.frame(a = c(1:5), b=c("df_1_1","df_1_2","df_2_3","df_1_1","df_2_4"))
match = "_1_1"
library("stringr")
library("microbenchmark")
microbenchmark(
grepl("_1_1$", df$b),
grep("_1_1", df$b),
grep("_1_1", df$b, fixed=TRUE),
endsWith(df$b, "_1_1"),
stringr::str_ends(df$b, "_1_1")
)
Unit: microseconds
expr min lq mean median uq max neval
grepl("_1_1$", df$b) 8.903 10.5985 11.68160 11.4215 12.2405 30.818 100
grep("_1_1", df$b) 9.020 10.0210 10.87328 10.8610 11.3625 15.101 100
grep("_1_1", df$b, fixed = TRUE) 3.709 4.7350 5.22625 5.2385 5.7445 7.059 100
endsWith(df$b, "_1_1") 2.049 2.7510 3.28577 3.1055 3.4460 23.906 100
str_ends(df$b, "_1_1") 35.657 38.2500 41.69787 40.4805 41.9560 131.970 100
grep
和grepl
幾乎相同。 就個人而言,我發現grep
由於其靈活性而更有用,所以我大部分時間都在使用它(例如,使用value=TRUE
您可以返回匹配的值)。
雖然stringr
和stringi
庫受到了應有的贊揚,但與所有內置解決方案相比, str_ends
的速度卻出奇地慢。 當您需要靈活性並且發現自己構建復雜的字符串匹配時, stringr
可能是正確的選擇,但基本解決方案適用於大多數用例,在這種情況下,速度要快得多。
內置的endsWith
勝過一切。 它是在純 C 中實現的專用且高度優化的解決方案。
正確的調用(沒有subset
)是:
df[endsWith(df$b, "_1_1"), ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.