【问题标题】:R - Extract portions of matching and non matching stringsR - 提取部分匹配和不匹配的字符串
【发布时间】:2018-04-09 16:23:23
【问题描述】:

我需要在两列之间提取匹配和不匹配的字符串部分:

x <- c("apple, banana, pine nuts, almond")
y <- c("orange, apple, almond, grapes, carrots")
j <- data.frame(x,y)

获得:

yonly <- c("orange, grapes, carrots")
xonly <- c("banana, pine nuts")
both <- c("apple, almond")
k <- data.frame(cbind(x,y,both,yonly,xonly))

我研究了 str_detect、intersect 等,但这些似乎需要对现有细胞进行大手术才能将它们分成不同的细胞。这是一个包含其他列的相当大的数据集,所以我不想过多地操纵它。你能帮我想出一个更简单的解决方案吗?

谢谢!

【问题讨论】:

    标签: r string dataframe string-comparison


    【解决方案1】:

    您可以使用setdiffintersect

    > j <- data.frame(x,y, stringsAsFactors = FALSE)
    > X <- strsplit(j$x, ",\\s*")[[1]]
    > Y <- strsplit(j$y, ",\\s*")[[1]]
    > 
    > #Yonly
    > setdiff(Y, X)
    [1] "orange"  "grapes"  "carrots"
    > 
    > #Xonly
    > setdiff(X, Y)
    [1] "banana"    "pine nuts"
    > 
    > #Both
    > intersect(X, Y)
    [1] "apple"  "almond"
    

    【讨论】:

    • 如果 OP 在j 中有不止一行并且是专用的'verser,他们可以扩展它以使用列表列:j %&gt;% mutate_all(funs(str_split(., pattern = ", "))) %&gt;% mutate(xonly = map2(x, y, setdiff), yonly = map2(y, x, setdiff), both = map2(x, y, intersect)) ... 需要 purrr、stringr、dplyr ,也许更多。
    【解决方案2】:

    如您所述,要创建更长的数据框 j 的额外列,您可以使用 mapply 和 Jilber Urbina 的答案中使用的方法...

    #set up data
    x <- c("apple, banana, pine nuts, almond")
    y <- c("orange, apple, almond, grapes, carrots")
    j <- data.frame(x,y,stringsAsFactors = FALSE)
    
    j[,c("yonly","xonly","both")] <- mapply(function(x,y) {
                        x2 <- unlist(strsplit(x, ",\\s*"))
                        y2 <- unlist(strsplit(y, ",\\s*"))
                        yonly <- paste(setdiff(y2, x2), collapse=", ")
                        xonly <- paste(setdiff(x2, y2), collapse=", ")
                        both <- paste(intersect(x2, y2), collapse=", ")
                        return(c(yonly, xonly, both))      },
                                            j$x,j$y)
    
    j
                                     x                                      y                   yonly             xonly          both
    1 apple, banana, pine nuts, almond orange, apple, almond, grapes, carrots orange, grapes, carrots banana, pine nuts apple, almond
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 2014-07-20
      相关资源
      最近更新 更多