作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在两列之间匹配一串单词并返回不匹配的单词。
示例数据框:
data = data.frame(animal1 = c("cat, dog, horse, mouse", "cat, dog, horse", "mouse, frog", "cat, dog, frog, cow"), animal2 = c("dog, horse, mouse", "cat, horse", "frog", "cat, dog, frog"))
animal1 animal2 unique_animal
1 cat, dog, horse, mouse dog, horse, mouse cat
2 cat, dog, horse cat, horse dog
3 mouse, frog frog mouse
4 cat, dog, frog, cow cat, dog, frog cow
library(qualV)
common <- function(a,b) {
a2 <- strsplit(a,'')[[1]]
b2 <- strsplit(b,'')[[1]]
if(length(a2) < length(b2)) {
a2[(length(a2)+1):length(b2)] <- ' '
} else if(length(a2) > length(b2)) {
b2[(length(b2)+1):length(a2)] <- ' '
}
LCS(a2,b2)
}
result <- NULL
data$animal1 <- as.character(data$animal1)
data$animal2 <- as.character(data$animal2)
for (i in 1:nrow(data)){
data_temp <- data[i,]
z <- common(data_temp$animal1,data_temp$animal2)
paste0(z$LCS, collapse = '') # common string
x <- z$a[which(!seq(1,max(z$va)) %in% z$va)] # non-matching elements in `a`
x <- paste(x, collapse='' )
data_temp$unique_animal <- x
result <- rbind(data_temp, result)
}
animal1 animal2 unique_animal
1 cat, dog, horse, mouse dog, horse, mouse cat,
2 cat, dog, horse cat, horse , dog
3 mouse, frog frog mouse,
4 cat, dog, frog, cow cat, dog, frog ,
最佳答案
在 ,\\s*
处拆分列后,我们可以使用 map2
做对应list
之间的比较带有 setdiff
的元素
library(dplyr)
library(purrr)
library(stringr)
data %>%
mutate(unique_animal = map2_chr(strsplit(as.character(animal1), ",\\s+"),
strsplit(as.character(animal2), ",\\s+"),
~ str_c(setdiff(.x, .y), collapse=", ")))
# animal1 animal2 unique_animal
#1 cat, dog, horse, mouse dog, horse, mouse cat
#2 cat, dog, horse cat, horse dog
#3 mouse, frog frog mouse
#4 cat, dog, frog, cow cat, dog, frog cow
关于r - 匹配单词串并返回不匹配的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61486876/
我是一名优秀的程序员,十分优秀!