[英]In R - Reading fixed number of csv files from folder and create dataframe based on selected files
[英]Reading files from folder and storing them to dataframe in R
我的目标最终是建立一个分类器-类似于垃圾邮件检测器。
但是,我不确定如何读取包含将输入分类器的文本并将其存储到数据框的文本文件。
因此,假设我已经将一个文本文件组装到一个文件夹中(原始文本最初存储在记事本中,然后从原始文本中保存到txt文件中),其名称指示其内容,例如xx_xx_xx__yyyyyyyyyyyy_zzzzz,其中xx是代表日期的数字,yyyyyyyyy将是代表主题的字符串,而zzzz将是代表源的字符串。 yyyyyyyyyy和zzzzzzz的长度是可变的。
我的目标是创建一个功能,该功能将遍历文件,读取文件,并将文件名中包含的信息存储在数据框的单独列中,例如“日期”,“主题”,“源”和文本第四列中的内容(例如“内容”)。
有什么想法可以实现吗?
您的建议将不胜感激。
嗨,这是一个可能的答案,我将结果存储在列表中而不是数据帧中,但是您可以使用do.call(rbind.data.frame,result)从一个转换为另一个
require(stringr)
datawd<-"C:/my/path/to/folder/" # your data directory
listoffiles<-list.files(str_c(datawd)) # list of files
listoffiles<-listoffiles[grep(".txt",listoffiles)] # only extract .txt files
my_paths<-str_c(datawd,listoffiles) # vector of path
# the following works with windows only
progress<-winProgressBar(title = "loading text files",
label = "progression %",
min = 0,
max = length(my_paths),
initial = 0,
width = 400)
#000000000000000000000000000000000000000 loop
for (i in 1:length(chemins)){
result<-list()
setWinProgressBar(progress,i,label=listoffiles[i])
the_date<-sapply(strsplit(listoffiles[i],"_"),"[[",1)
the_theme<-sapply(strsplit(listoffiles[i],"_"),"[[",2)
the_source<-sapply(strsplit(listoffiles[i],"_"),"[[",3)
# open connexion with read
con <- file(my_paths[i], open = "r")
# readlines returns an element per line, here I'm concatenating all,
#you will do what you need....
the_text<- str_c(readLines(con,warn = FALSE))
close(con) # closing the connexion
result[[i]]<-list()
result[[i]]["date"]<-the_date
result[[i]]["source"]<-the_source
result[[i]]["theme"]<-the_theme
result[[i]]["text"]<-the_text
}
#000000000000000000000000000000000000000 end loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.