【问题标题】:Creating a data frame with the contents of multiple txt files创建一个包含多个txt文件内容的数据框
【发布时间】:2017-02-17 15:18:09
【问题描述】:

我是 R 编程新手,在尝试从多个文本文件创建一个数据框时遇到了困难。我有一个包含 100 多个文本文件的目录。每个文件都有不同的文件名,但内容具有相似的格式,例如3 列(姓名、年龄、性别)。我想将每个文本文件加载到 R 中并将它们合并到 1 个数据框中。

到目前为止我有:

txt_files = list.files(path='names/', pattern="*.txt");
do.call("rbind", lapply(txt_files, as.data.frame))

这已创建文件名列表,但未创建文件内容。我能够读取一个文件的内容并创建一个数据框,但我似乎无法一次为多个文件执行此操作。如果有人可以提供任何帮助,我将非常感激,因为我完全陷入困境!

提前致谢!

【问题讨论】:

  • read.table替换as.data.frame
  • 谢谢@Rich。我试过了,由于某种原因它只返回输出:NULL > txt_files >character(0).....我确实遇到了“文件错误(文件,“rt”):无法打开连接”的问题我已经解决但没有任何运气的错误。不过感谢您的帮助。

标签: r


【解决方案1】:

我想你可能想要这样的东西:

# Put in your actual path where the text files are saved
mypath = "C:/Users/Dave/Desktop"
setwd(mypath)

# Create list of text files
txt_files_ls = list.files(path=mypath, pattern="*.txt") 
# Read the files in, assuming comma separator
txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = T, sep =",")})
# Combine them
combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame)) 

当我创建几个示例文本文件时,至少这对我有用。 希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多