【问题标题】:How to find document frequency in R?如何在 R 中查找文档频率?
【发布时间】:2026-02-06 07:05:01
【问题描述】:

我需要有关此问题的帮助才能在 R 中创建一个程序,该程序可以找到: - 索引器处理的最小文档数为 4。 -从每个文档中提取所有术语以构建矩阵,其中包含每个文档中的术语频率(要打印)。 - 打印每个术语及其 DF(文档频率)

我尝试通过for循环和函数输入文件,但没有成功,我不知道如何解决这个问题

analyze <- function(filename) {
    # Plots the average, min, and max inflammation over time.
    # Input is character string of a csv file.
    dat <- read.csv(file = filename, header = FALSE)
    avg_day_inflammation <- apply(dat, 2, mean)
    plot(avg_day_inflammation)
    max_day_inflammation <- apply(dat, 2, max)
    plot(max_day_inflammation)
    min_day_inflammation <- apply(dat, 2, min)
    plot(min_day_inflammation)
  }

  analyze("E://FCI-H//level 3 - Second Semester//Information Retrival//Section//assignment//assignment3//1.csv")

此代码向我显示了一个错误,但我希望通过打开 5 个以上的文件并将它们组合然后制作一个矩阵并找到文档频率来解决此问题

【问题讨论】:

  • 这显然是一个单一的练习。因此,我将在这里留下一些提示和一条评论。评论:请正确格式化您的问题。从你的问题中不清楚你在回答什么。例如,如果这是您需要帮助的问题,请将错误添加到您的问题中。提示:(提示1)尝试查看?colMeans,(提示2)尝试read.csv(file.choose()),看看您是否可以手动打开文件。 (提示 3)如果您想打印一些东西,请尝试使用 print 函数,而不是使用绘图进行可视化。

标签: r dataframe


【解决方案1】:

这是我的问题的解决方案

library(tm)

mypath = "E://FCI-H//level 3 - Second Semester//Information Retrival//Section//assignment//assignment3" setwd(mypath)


txt_files_ls = list.files(path=mypath, pattern="*.txt")  txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = F, sep ="/")})

combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame))

names(combined_df) <- "text" myCorpus <- Corpus(VectorSource(combined_df$text))

tdm <- TermDocumentMatrix(myCorpus,control = list(removePunctuation = TRUE, stopwords = TRUE)) dtm <- DocumentTermMatrix(myCorpus, control = list(weighting = function(x) weightTfIdf(x, normalize = FALSE), stopwords = TRUE))

inspect(tdm) inspect(dtm)

【讨论】: