簡體   English   中英

如何使用R導入基於標題的多個文本文件?

[英]How to import multiple text files based on titles using R?

我正在使用'readtext'包在特定目錄中導入多個文本文件。

library(readtext)
DATA_DIR <- system.file("extdata/", package = "readtext")
readtext(paste0(DATA_DIR, "/txt/UDHR/*"))

我的問題是:有什么方法可以根據標題導入文本文件? 我想導入標題中包含特定單詞(例如apple)的文件。

提前謝謝你的幫助。

這應該做您想要的。

# List all txt files including sub-folders
list_of_files <- list.files(path = "C:\\your_path_here\\", recursive = TRUE,
                            pattern = "the_run", full.names = TRUE)

library(data.table)

# Read all the files and create a FileName column to store filenames
DT <- rbindlist( sapply(list_of_files, fread, simplify = FALSE),
                 use.names = TRUE, idcol = "FileName" )

在這個愚蠢的示例中,我設置了一個父文件夾,其中包含3個子文件夾。 在每個子文件夾中,我有5個文本文件:the_run1.txt,the_run2.txt,the_run3.txt,run1.txt和run2.txt。 我正在找到父文件夾,並在所有子文件夾中查找文件名中帶有“ the_run”的文本文件。 就是這樣 我創建了這9個文件的列表(3個文件夾中的3個文件),並循環瀏覽此列表以將所有內容加載到單個數據表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM