r 逐行比较两列中的文本
r compare text in two columns by row
我想将 X1 列中的文本与 X2 列中的文本进行比较
和
生成出现在 X1 但不出现在 X2 中的单词列表,反之亦然。例如:
df <- data.frame("X1" = c("the fox ate grapes", "the cat ate"), "X2" = c("the fox ate watermelon", "the cat ate backwards"))
我正在尝试生成列,例如
X3-葡萄西瓜
X4 - 向后
数据框有数百行,部分单元格中的文本多达50个字左右。
我不明白你想如何组织 X3
和 X4
中的输出,但这也许有帮助:
words_x1 <- (df$X1 %>% paste(collapse = " ") %>% str_split(" "))[[1]] %>% unique()
words_x2 <- (df$X2 %>% paste(collapse = " ") %>% str_split(" "))[[1]] %>% unique()
c(words_x1[!(words_x1 %in% words_x2)], words_x2[!(words_x2 %in% words_x1)])
我认为你想要实现的是这样的(请注意,我使用的是 tibble
,因为它似乎不适用于 data.frame
。
library(dplyr)
library(purrr)
df <- tibble(
X1 = c("the fox ate grapes", "the cat ate"),
X2 = c("the fox ate watermelon", "the cat ate backwards")
)
myfunction <- function(x1, x2) {
w1 <- strsplit(x1, " ")[[1]]
w2 <- strsplit(x2, " ")[[1]]
c(w1[!(w1 %in% w2)], w2[!(w2 %in% w1)])
}
map2(df$X1, df$X2, myfunction)
我想将 X1 列中的文本与 X2 列中的文本进行比较 和 生成出现在 X1 但不出现在 X2 中的单词列表,反之亦然。例如:
df <- data.frame("X1" = c("the fox ate grapes", "the cat ate"), "X2" = c("the fox ate watermelon", "the cat ate backwards"))
我正在尝试生成列,例如 X3-葡萄西瓜 X4 - 向后
数据框有数百行,部分单元格中的文本多达50个字左右。
我不明白你想如何组织 X3
和 X4
中的输出,但这也许有帮助:
words_x1 <- (df$X1 %>% paste(collapse = " ") %>% str_split(" "))[[1]] %>% unique()
words_x2 <- (df$X2 %>% paste(collapse = " ") %>% str_split(" "))[[1]] %>% unique()
c(words_x1[!(words_x1 %in% words_x2)], words_x2[!(words_x2 %in% words_x1)])
我认为你想要实现的是这样的(请注意,我使用的是 tibble
,因为它似乎不适用于 data.frame
。
library(dplyr)
library(purrr)
df <- tibble(
X1 = c("the fox ate grapes", "the cat ate"),
X2 = c("the fox ate watermelon", "the cat ate backwards")
)
myfunction <- function(x1, x2) {
w1 <- strsplit(x1, " ")[[1]]
w2 <- strsplit(x2, " ")[[1]]
c(w1[!(w1 %in% w2)], w2[!(w2 %in% w1)])
}
map2(df$X1, df$X2, myfunction)