【问题标题】:read multiple files into r, no column names将多个文件读入r,没有列名
【发布时间】:2014-10-16 10:23:41
【问题描述】:

我有许多 .txt 文件,数据以逗号分隔。没有标题。每个都包含相同的信息,但不同的年份:姓名、性别和姓名的数量。

我可以在一个rbind 中读取它们,但是我丢失了年份信息 - 年份仅包含在文件名中...y1920.txty1995.txty2002.txt 等等。

我对 R 很陌生。

对于rbind他们,我使用了do.call(file, rbind),其中file是data.frames的列表。

【问题讨论】:

    标签: r filenames rbind


    【解决方案1】:

    Plyr 有一个很好的工作流程,假设您的文件都在当前工作目录中:

    library(plyr)
    years <- ldply(list.files(pattern="y\\d{4}\\.txt"), 
                   function(file){ 
                     data <- read.csv(file, header=F); 
                     data$date <- gsub("y","",gsub("\\.txt","", file)); 
                     data})
    

    如果您想指定您的文件,例如files &lt;- c("y1995.txt", "y1996.txt"),您可以将ldply (list.files(...)) 的第一个参数替换为files

    【讨论】:

    • +1 非常好。与for 循环基本相同,但跳过rbind 部分(或rbindlist,如果您进入data.tables)
    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 2017-04-21
    • 2019-07-03
    • 2021-12-03
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多