【问题标题】:R, String Match or String match combination of stringsR,字符串匹配或字符串匹配字符串组合
【发布时间】:2017-05-24 06:14:07
【问题描述】:

我有一组字符串,例如 "United Kingdom","United States","China","India", And Other String 必须与上面的字符串集合进行比较,并且可以是上面字符串集合中以“|”分隔的多个值的组合.

如例:

String1 <- "China"
String2 <- "United States|China"
String3 <- "United States|India|China"
SetoFStrings <- c("United Kingdom","United States","China","India")

所以在所有情况下,当将 String1、String2、String3 与 SetofStrings 进行比较时,Result 值必须为 true。这是怎么做到的

【问题讨论】:

    标签: r string grepl


    【解决方案1】:

    我们可以使用anygrepl

    any(grepl(String1, SetoFStrings))
    #[1] TRUE
    any(grepl(String2, SetoFStrings))
    #[1] TRUE
    any(grepl(String3, SetoFStrings))
    #[1] TRUE
    

    如果目标是在输入帖子中创建“字符串”

    sapply(dat2$Strings, function(pat) any(grepl(pat, SetoFStrings)))
    

    数据

    dat1 <- data.frame(Col1 = c('China', 'UnitedStates', 'India'), stringsAsFactors= FALSE)
    dat2 <- data.frame(Strings =  Reduce(function(...) paste(..., sep="|"), 
               dat1$Col1, accumulate = TRUE), stringsAsFactors=FALSE) 
    

    【讨论】:

    • 又如何往前走,String1,String2,String3在一个dataframe的一列,整列都应该和SetoFStrings比较?使用应用函数?
    • @Shivpe_R cmets 不清楚。你能更新你的问题和预期的输出吗
    • @Shivpe_R 也许any(grepl(paste(unique(as.character(yourdata$Col)), collapse="|"), SetoFStrings))
    • 我在数据框中有一列,其中包含诸如 String1、String2、String3 之类的值直到大约 200 个值,并且列中的每个值都应与 SetoFStrings 进行比较,因此在与 SetoFStrings 比较后期待一列,喜欢 TRUE TRUE FALSE 。等等
    • @Shivpe_R 你有相同的SetoFStrings 来比较吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多