Enrique Enrique - 11 months ago 47
R Question

Create a list with empty files and a list with not empty files

I've got a lot of files in a folder, many of them are empty and others with data inside.

What I'm trying to do is this:

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

Using this list, I'm trying to skip empty files using the method explained by @nrussell How to skip empty files when importing text files in R?

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

And (not empty files)

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

The difference between @nrussell and mine is that I want to create a list of empty files and another list with not empty files. I'd like to know how many files are empty and how many are not empty.

Answer Source
# 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)]