我需要提取字符串中匹配的部分和两列之间不匹配的部分:
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等,但这些似乎需要对现有细胞进行重大手术,将它们分离成不同的细胞。这是一个与其他列相当大的数据集,所以我不想过多地操作它。你能帮我想出一个更简单的解决方案吗?
谢谢!
发布于 2018-04-09 16:29:24
您可以使用setdiff和intersect
> 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"发布于 2018-04-09 17:08:27
为了像您所描述的那样创建一个更长的dataframe j的额外列,您可以使用mapply与Jilber的答案中使用的方法。
#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, almondhttps://stackoverflow.com/questions/49737447
复制相似问题