使用grepl(R)查找哪个表达式首先出现在字符串中?

时间:2017-01-26 17:06:48

标签: r regex grepl

我使用R进行数据分析,我有一个字符串变量,列出了调查中管理措施的顺序。这是一个受访者的字符串变量:

"pimgrwelcomerealstartnamelessTaskinstruct_itemshealth_itemsinstruct_selfsexp_instiat_esteemdebriefing1lastpage"

我有什么方法可以使用" grepl"测试这些措施的顺序?例如,我可以看看" health_items"字符串中的字符串早于#34; instruct_self" (在上面的字符串中是真的)?如果是这样,我想创建一个虚拟变量,以便测试顺序效果。

谢谢大家。

1 个答案:

答案 0 :(得分:2)

我不是写这个作为答案而只是分享我对这个问题的看法:希望有人帮助grepl

您可以使用2种方法提取子字符串的位置,这些方法可用于检查第一个字符串是否位于第二个字符串之前:

regexpr("health_items", s). #where s is your string
# or
library(stringr)
str_locate(s, "health_items")

所以要知道哪个是第一个:

sapply( c("health_items", "instruct_self"), function(x) str_locate(s, x))
# this should return a vector with the start index.
相关问题