【问题标题】:r compare text in two columns by rowr 逐行比较两列中的文本
【发布时间】:2021-03-13 20:44:48
【问题描述】:

我想将 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个字左右。

【问题讨论】:

    标签: r string text iteration corpus


    【解决方案1】:

    我不明白您想如何组织 X3X4 中的输出,但也许这会有所帮助:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      相关资源
      最近更新 更多