我有一个由 tm 的 TermDocumentMatrix 生成的稀疏术语文档矩阵。
我正在尝试编写一个函数,它以两个文档名称和 k 作为参数,查找在两个文档中出现的所有术语,按术语的字数降序排列该列表,并返回前 k 个。每个术语中的单词用下划线分隔(如 bob_raids_crops)。
这是一个玩具示例(我按长度而不是字词字数排序):
library(tm)
library(dplyr)
data("crude")
tdm <- TermDocumentMatrix(crude,
control = list(removePunctuation = TRUE,
stopwords = TRUE))
df <- data.frame(term = row.names(tdm), as.matrix(tdm[, c("127", "144")]), row.names = NULL)
df$in.both <- ifelse(df[,2]>0 & df[,3]>0, TRUE, FALSE)
df <- df%>%
subset(in.both == TRUE) %>%
arrange(desc(str_length(term))) %>%
select(term) %>%
top_n(5,str_length(term))
df
返回:
term
1 companies
2 markets
3 market
4 prices
5 reuter
我打算编写一个函数,但想知道是否有现成的方法可以做到这一点。如果不是,我可以使上述更有效(比如避免数据帧)吗?
最佳答案
这是一个解决方案,使用 rowSums
对出现的单词求和,使用 full_join
连接为每个文档制作的 2 df。应用 na.omit()
确保只计算出现在两个文档中的单词。
对于文档 144,单词按降序排列。
library(tm)
#> Lade nötiges Paket: NLP
#library(dplyr)
library(tidyverse)
data("crude")
tdm <- TermDocumentMatrix(crude,
control = list(removePunctuation = TRUE,
stopwords = TRUE))
one_44 <- rowSums(as.matrix(tdm[, "144"])) %>%
as.data.frame() %>%
rownames_to_column() %>%
rename("F" = ".") %>%
mutate(text = "one_44")
one_27 <- rowSums(as.matrix(tdm[, "127"])) %>%
as.data.frame() %>%
rownames_to_column() %>%
rename("F" = ".") %>%
mutate(text = "one_27")
one_27 %>% full_join(one_44, by = c('rowname', "F", 'text')) %>%
filter(F >0) %>% #distinct(text)
pivot_wider(names_from = text, values_from = F) %>%
na.omit() %>%
arrange(desc(one_44))
#> # A tibble: 10 × 3
#> rowname one_27 one_44
#> <chr> <dbl> <dbl>
#> 1 oil 5 12
#> 2 said 3 11
#> 3 prices 3 5
#> 4 market 1 3
#> 5 markets 1 2
#> 6 companies 1 1
#> 7 last 1 1
#> 8 price 2 1
#> 9 reuter 1 1
#> 10 two 1 1
关于r - 查找一对文档之间的重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74505683/