【问题标题】:Use grepl (R) to find which expression comes first in a string?使用 grepl (R) 查找字符串中的第一个表达式?
【发布时间】:2017-01-26 17:06:48
【问题描述】:

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

"pimgrwelcomerealstartnamelessTaskinstruct_itemshealth_itemsinstruct_selfsexp_instiat_esteemdebriefing1lastpage"

有什么方法可以使用“grepl”来测试这些度量的顺序吗?例如,我可以查看字符串中的“health_items”是否比“instruct_self”更早(在上面的字符串中是这样)?如果是这样,我想创建一个虚拟变量,以便测试订单效果。

谢谢大家。

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    我写这个不是为了回答,只是为了分享我对这个问题的想法:希望有人能帮助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.
    

    【讨论】:

    • 虽然没有使用grepl,但是这个方案完美的解决了问题,应该算是问题的答案了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多