[英]R: Filtering a data frame by matching partial from a list using "grepl"
我有一個大數據框 ( df
) 我想通過搜索列 ( df$column
) 和列表 ( aList
) 之間的部分匹配來過濾。
aList <- c("ID1", "ID2", "ID3")
我用於過濾的數據框中的變量包含可能僅以列表中的值開頭的值。 示例: ID1_23
或ID2AV
。
然后,我想使用grepl
或類似方法在我的數據框列中搜索以aList
的值開頭的任何值。 我在僅搜索單個值時處理這種方式的方法是:
library(dplyr)
newDf <- df %>% filter(grepl("^ID1", column))
然后我的問題出現在如何對我的列表中的所有值進行類似處理。 我嘗試了以下方法:
dummyList <- c()
for (i in 1:length(aList)){
list1 <- dplyr::filter(grepl(paste("\"^", aList[i], "\""), df$column))
rbind(list1, dummyList)
}
這為我提供了以下錯誤代碼:
Error in UseMthod("filter_") :
no applicable method for ´filter_´ applied to an obecjt of class "logical"
誰能幫我?
謝謝!
我們可以將這些值paste
在一起
library(tidyerse)
df %>%
filter(grepl(str_c("^(", str_c(aList, collapse="|"), ")"), column))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.