【问题标题】:Document Term Matrix with two dataframes in RR中带有两个数据框的文档术语矩阵
【发布时间】:2021-10-05 10:46:38
【问题描述】:

我想使用两个数据框在 R 中创建一个文档术语。

例如,第一个数据框包含文本。

df1

category     text
person1      "hello word I like turtles"
person2      "re: turtles! I think turtles are stellar!"
person3      "sunflowers are nice."

第二个数据框有一列包含所有感兴趣的术语。

df2

col1    term
x       turtles
y       hello
w       sunflowers
f       I

生成的矩阵将显示每个人对df2$terms 中每个单词的使用。

结果

category    turtles     hello     sunflowers     I         
person1       1           1            0         1
person2       2           0            0         1
person3       0           0            1         0

帮助!

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这是一个使用正则表达式的 hack,应用和合并:

    category = c('person1','person2','person3')
    text=c("hello word I like turtles", "re: turtles! I think turtles are stellar!", "sunflowers are nice.")
    df1 = data.frame(category=category,text=text)
    df2 = data.frame(term=c('turtles','hello','sunflowers','I'))
    
    f = function(pattern){
      
      patterncount = function(x){ # Counts occurrence of pattern in a string
        
        if (grepl(x, pattern=pattern)){
          
          length(gregexpr(x, pattern=pattern)[[1]])
        } else{
          0
        }
      }
      sapply(df1$text, FUN = patterncount)
      
    }
    
    df3 = data.frame(sapply(df2$term, FUN=f))
    df3$text = row.names(df3)
    
    result = merge(df1, df3, by='text')
    

    【讨论】:

    • 嗨@njp!谢谢!该解决方案确实出现此错误: xj[i] 中的错误:'closure' 类型的对象不是子集
    • 嗨 mk2080。抱歉,我错过了一个右大括号。立即尝试。
    【解决方案2】:

    使用来自stringrstr_count -

    library(stringr)
    cbind(df1[1], sapply(df2$term, function(x) str_count(df1$text, x)))
    
    #  category turtles hello sunflowers I
    #1  person1       1     1          0 1
    #2  person2       2     0          0 1
    #3  person3       0     0          1 0
    

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 2018-06-24
      • 2015-05-05
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      相关资源
      最近更新 更多