2016-04-27 34 views
-1

我有一个包含过多文件的目录;每个文件具有相同的结构:将多个文件读取到数据框中

Nodes: 6606 
Edges: 382386 
Average degree: 115.76930063578565 
Average clustering: 0.11213868344294504 
Modularity: 0.6021229084216876 
Giant component: 6598 

使用list.files()功能我读目录的内容:

files <- list.files(path = "test", pattern = "netstat*", full.names = TRUE) 

然后我用lapply()函数读取文件转换成数据帧的名单:

data1 <- lapply(files, read.table, sep = ":", row.names = 1) 

最后我将列表转换为数据框并重命名行名:

data2 <- t(do.call(data.frame, data1)) 
rownames(data2) <- 1:nrow(data) 

最终的数据是这样的:

> head(data2) 
    Nodes Edges Average degree Average clustering Modularity Giant component 
1 6606 382386  115.769301   0.11213868 0.6021229   6598 
2 5157 20292  7.869692   0.07020251 0.8195294   5125 
3 5177 20148  7.783658   0.07640135 0.9030172   5102 
4 5689 29559  10.391633   0.08480404 0.7104452   5626 
5 5985 32086  10.722139   0.06803845 0.7189815   5938 
6 5829 26449  9.074970   0.05963236 0.7061715   5770 

我的问题:是否有更优雅的方式来做到这一点?特别是最后的命令 - 我手动重命名行 - 在某种程度上不符合优雅的R编程。

回答

1

我们可以读取使用fread文件和data.tablelist在S转换成一个单一的与data.tablerbindlist

library(data.table) 
rbindlist(lapply(files, fread))