r - 快速组合和转置许多固定格式的数据集文件

标签 r fread read.csv fixed-format

我拥有:~100 个 txt 文件,每个文件有 9 列和 >100,000 行 我想要的:一个组合文件,其中只有 2 列,但包含所有行。那么应该将其转置为 >100,000 列和 2 行的输出。

我创建了以下函数来系统地浏览文件夹中的文件,提取我想要的数据,然后在每个文件之后与原始模板连接在一起。

问题:这在我的小测试文件上运行良好,但是当我尝试在大文件上执行此操作时,我遇到了内存分配问题。我的 8GB RAM 还不够,我认为部分原因在于我编写代码的方式。

我的问题:有没有办法循环遍历文件,然后在最后一次加入所有文件以节省处理时间?

此外,如果这是放置此类内容的错误位置,那么有什么更好的论坛来获取 WIP 代码的输入?

##Script to pull in genotype txt files, transpose them, delete commented rows & 
## & header rows, and then put files together.

library(plyr)

## Define function
Process_Combine_Genotype_Files <- function(
        inputdirectory = "Rdocs/test", outputdirectory = "Rdocs/test", 
        template = "Rdocs/test/template.txt",
        filetype = ".txt", vars = ""
        ){

## List the files in the directory & put together their path
        filenames <- list.files(path = inputdirectory, pattern = "*.txt")
        path <- paste(inputdirectory,filenames, sep="/")


        combined_data <- read.table(template,header=TRUE, sep="\t")

## for-loop: for every file in directory, do the following
        for (file in path){

## Read genotype txt file as a data.frame
                currentfilename  <- deparse(substitute(file))
                currentfilename  <- strsplit(file, "/")
                currentfilename <- lapply(currentfilename,tail,1)

                data  <- read.table(file, header=TRUE, sep="\t", fill=TRUE)

                #subset just the first two columns (Probe ID & Call Codes)
                #will need to modify this for Genotype calls....
                data.calls  <- data[,1:2]

                #Change column names & row names
                colnames(data.calls)  <- c("Probe.ID", currentfilename)
                row.names(data.calls) <- data[,1]


## Join file to previous data.frame
                combined_data <- join(combined_data,data.calls,type="full")


## End for loop
        }
## Merge all files
        combined_transcribed_data  <- t(combined_data)
print(combined_transcribed_data[-1,-1])
        outputfile  <- paste(outputdirectory,"Genotypes_combined.txt", sep="/")        
        write.table(combined_transcribed_data[-1,-1],outputfile, sep="\t")

## End function
}

提前致谢。

最佳答案

尝试:

filenames <- list.files(path = inputdirectory, pattern = "*.txt")
require(data.table)
data_list <- lapply(filenames,fread, select = c(columns you want to keep))

现在您已经有了所有数据的列表。假设所有 txt 文件确实具有相同的列结构,您可以通过以下方式组合它们:

data <- rbindlist(data_list)

转置数据:

t(data)

(感谢 @Jakob H 在 fread 中select)

关于r - 快速组合和转置许多固定格式的数据集文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31039269/

相关文章:

r - 如何将多行Excel单元格读入R

R:data.table .动态聚合列日期列

R data.table fread 使用没有标题的命名 colClasses(例如没有 col.names?)

R 中不带引号的 read.csv 行

r - read.csv 中的多字节字符串无效

c++ - 为什么在构造函数中使用 fread 时我的程序会崩溃?

r - 带有多行标题的print.xtable?

r - 用 hexSticker 修剪六边形形状?

r - 如何按小数值过滤数值?

php - 如果unread_bytes == 0,则取消阻塞fread(),而不会使流连接超时