2016-11-03 55 views
0

我在文件夾中有很多文件,其中許多文件都是空的,而其他文件夾裏面有數據。用空文件和非空文件列表創建列表

我想要做的是這樣的:

#Load all data in a list 
file_all <- list.files(file.path(getwd(), "testall"), pattern = "\\.txt$") 

使用這個列表中,我試圖跳過使用@nrussell How to skip empty files when importing text files in R?

library(plyr) 
df_list <- lapply(files, function(x) { 
    if (!file.size(x) == 0) { 
     list.files(x) 
    } 
}) 

和(說明的方法空文件不是空文件)

df_list2 <- lapply(files, function(x) { 
    if (file.size(x) == 0) { 
     list.files(x) 
    } 
}) 

@nrussell和我之間的區別是,我想c創建一個空文件列表和另一個沒有空文件的列表。我想知道有多少文件是空的,有多少不是空的。

+0

爲什麼不使用'apply'函數將文件存儲在兩個不同的向量中。 –

+0

@EliSadoff這是一個錯誤,抱歉。我存儲在兩個不同的向量中。 – Enrique

+0

執行此操作:list.of.files < - file.info(dir()) sizes < - file.info(dir())$ size list.of.non.empty.files < - rownames(list。 of.files)[which(sizes!= 0)]然後你必須從非空文件列表中讀入 list.of.empty.files < - rownames(list.of.files) [其中(尺寸== 0)] –

回答

2
# create a list of files in the current working directory 
list.of.files <- file.info(dir()) 

# get the size for each file 
sizes <- file.info(dir())$size 

# subset the files that have non-zero size 
list.of.non.empty.files <- rownames(list.of.files)[which(sizes != 0)] 

# here you can further subset that list by file name, eg - if I only want all the files with extension .mp3 
list.of.non.empty.files[grep(".mp3", list.of.non.empty.files)] 


# get the empty files 
list.of.empty.files <- rownames(list.of.files)[which(sizes == 0)] 
+0

謝謝!這是完美的。 – Enrique