【问题标题】:How to match strings in different combinations in R如何在R中匹配不同组合的字符串
【发布时间】:2017-06-22 20:55:51
【问题描述】:

我有一个数据框 df,其中的单词由 + 分隔,但我不希望在执行分析时顺序很重要。例如,我有

df <- as.data.frame(
      c(("Yellow + Blue + Green"),
        ("Blue + Yellow + Green"),
        ("Green + Yellow + Blue")))

目前,它们被视为三个独特的响应,但我希望它们被视为相同。我尝试过诸如ifelse 语句之类的蛮力方法,但它们不适合大型数据集。

有没有办法重新排列术语以使它们匹配,或者像反向 combn 函数那样识别它们是相同的组合但顺序不同?

谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:
    #DATA
    df <- data.frame(cols = 
                     c(("Yellow + Blue + Green"),
                       ("Blue + Yellow + Green"),
                       ("Green + Yellow + Blue"),
                       ("Green + Yellow + Red")), stringsAsFactors = FALSE)
    
    #Split, sort, and then paste together
    df$group = sapply(df$cols, function(a)
        paste(sort(unlist(strsplit(a, " \\+ "))), collapse = ", "))
    df
    #                   cols               group
    #1 Yellow + Blue + Green Blue, Green, Yellow
    #2 Blue + Yellow + Green Blue, Green, Yellow
    #3 Green + Yellow + Blue Blue, Green, Yellow
    #4  Green + Yellow + Red  Green, Red, Yellow
    
    #Or you can convert to factors too (and back to numeric, if you like)
    df$group2 = as.numeric(as.factor(sapply(df$cols, function(a)
            paste(sort(unlist(strsplit(a, " \\+ "))), collapse = ", "))))
    df
    #                   cols               group group2
    #1 Yellow + Blue + Green Blue, Green, Yellow      1
    #2 Blue + Yellow + Green Blue, Green, Yellow      1
    #3 Green + Yellow + Blue Blue, Green, Yellow      1
    #4  Green + Yellow + Red  Green, Red, Yellow      2
    

    【讨论】:

    • 谢谢d.b!效果很好。我应该更具体地说明的一件事是,我仍然希望它采用 a + b + c 格式,但通过更改 collapse 语句可以轻松修复它。
    【解决方案2】:

    我想提供我对此的看法,因为不清楚您想要输出什么格式:

    我使用包stringriterators。使用d.b.创建的df

    search <- c("Yellow", "Green", "Blue")
    L <- str_extract_all(df$cols, boundary("word"))
    sapply(iter(L), function(x) all(search %in% x))
    [1]  TRUE  TRUE  TRUE FALSE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多