R - 提取匹配和非匹配字符串的部分

时间:2018-04-09 16:23:24

标签: r string dataframe string-comparison

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

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,交叉等等,但这些似乎需要对现有细胞进行大手术以将它们分成不同的细胞。这是一个与其他列相关的大型数据集,因此我宁愿不要过多地操纵它。你能帮我提出一个更简单的解决方案吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用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"

答案 1 :(得分:1)

如您所述,要创建较长数据框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