子集不是基于完全匹​​配,而是基于 R 中的部分 [英] Subset not based on exact match, but partial in R

查看:24
本文介绍了子集不是基于完全匹​​配,而是基于 R 中的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这里的后续问题:根据前缀和后缀对字符串进行子集化

当你有这个命令时:

    d <- subset(b, b$X %in% test)  

此命令查找 b$X 中与 test 完全匹配的所有内容.我如何操纵它来说明 b$X 中的值包含 test 就足够了?
IE.如果 b$X 有一个值 "something" 并且 test"thing".那么我会认为这是一个匹配.

This command look for all in b$X that exactly matches test. How can I manipulate it to say its enough that the values in b$X contains test?
I.e. if b$X has a value "something" and test has "thing". Then I would regard this as a match.

重要更新!测试有 512 个值,而不仅仅是示例中的 1.

Important update! Test has 512 values, not only 1 as in the example.

推荐答案

您可以将 %in% 替换为 grepl:

You can replace %in% with grepl:

# examples
x <- c("thing", "something", "some", "else")
test <- c("thing", "some")

# exact match
x %in% test
# [1]  TRUE FALSE  TRUE FALSE

# substring match (regex)
pattern <- paste(test, collapse = "|") # create regex pattern
grepl(pattern, x)
# [1]  TRUE  TRUE  TRUE FALSE

任务的整个命令:

d <- subset(b, grepl(paste(test, collapse= "|"), b$X))

"|" 在正则表达式中表示逻辑.

The "|" means logical or in regular expressions.

这篇关于子集不是基于完全匹​​配,而是基于 R 中的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆