从具有文本列的给定data.frame中,我需要子集包含先前存储在向量中(或在第二个data.frame列中)的字符子串的行。
Example data:
require(stringi) # Used for generate random string
set.seed(1)
df <- as.data.frame(cbind(seq(from = 1, to = 10, by = 1), stri_rand_strings(10, 5)))
df
V1 V2
1 1 GNZuC
2 2 twed3
3 3 CAgNl
4 4 UizNm
5 5 vDe7G
6 6 N0NrL
7 7 TbUBp
8 8 fn6iP
9 9 oemYW
10 10 m1Tjg
如果我将搜索到的子串存储在矢量中,如图所示
tofind <- c("AgN", "bUB")
结果我需要获取以下data.frame
V1 V2
1 3 CAgNl
2 7 TbUBp
感谢您的帮助
答案 0 :(得分:0)
如果您更改tofind
向量(使用大写N),则此方法有效:
tofind <- c("AgN", "bUB")
df[grep(paste(tofind, collapse = "|"), df$V2),]
V1 V2
3 3 CAgNl
7 7 TbUBp
并使用subset
函数:
subset(df, grepl(paste(tofind, collapse = "|"), V2))
您使用grepl
代替grep
,因为subset
函数需要逻辑向量而非数字