aminards
aminards

Reputation: 421

How can I use lapply to remove empty rows from a List of dataframes?

I have a list of data frames. There are 28 data frames in my list. Some of the data frames have empty rows but not all. How can I use lapply or a similar function to remove empty rows from all data frames in the list?

Here is what I have tried which I modified from this question. Unfortunately, this returned only those rows that were empty.

#Get list of all files that will be analyzed
filenames = list.files(pattern = ".csv")

#read in all files in filenames
mydata_run1 = lapply(filenames, read.csv, header = TRUE, quote = "")

#Remove empty rows
mydata_run1 = lapply(mydata_run1, function(x) sapply(mydata_run1, nrow)>0)

Thank you.

Upvotes: 2

Views: 1191

Answers (1)

user5249203
user5249203

Reputation: 4648

I assume you want to remove empty rows when appeared across all columns. If so,

# remove row data if only all the columns have NA value. 
lapply(data, function(x){ x[rowSums(is.na(x)) != ncol(x),]})

output


$df1
  A B
1 1 4
3 3 6

$df2
  A  B
1 1 NA
3 3  6

data


data <- list(
            df1 = data.frame(A = c(1,NA,3), B = c(4, NA, 6)),
            df2 = data.frame(A = c(1,NA,3), B = c(NA, NA, 6)))

Upvotes: 1

Related Questions