Delete empty rows in df within for loop

Hi,
I need to import dataframes to R using for loop from a list:

file.list <- list.files(pattern='*.xls.*', recursive = TRUE)
df.list_excel <- lapply(file.list, read_excel)

for(i in 1:length(df.list_excel)) {  
assign(paste0("file_", i), df.list_excel[[i]])   
}

I need to delete empty rows in each df when importing dataframes. I tried two ways, neither worked:

library(janitor)

for(i in 1:length(df.list_excel)) {  
assign(paste0("file_", i), df.list_excel[[i]]) %>% remove_empty("rows")  
}

or

for(i in 1:length(df.list_excel)) {  
assign(paste0("file_", i), df.list_excel[[i]]) %>% na.omit  
}

Can anybody help me, please? Thanks a lot.

Hi,

Since I can't look at the specific data you're working with, I created a little example of my own to mimic what you are asking for:

library(dplyr)
library(janitor)

#Generate random data with missing rows
randomData = function(){
  data = data.frame(x = runif(10), y = runif(10))
  data[sample(c(1:10), sample(1:3, 1)),] = NA
  return(data)
}

df.list_excel = lapply(1:10, function(x) randomData())

#With apply
cleanedData = lapply(df.list_excel, function(x) x %>% remove_empty("rows"))

#With for loop
cleanedData = list()
for(i in 1:length(df.list_excel)){
  cleanedData[[i]] = df.list_excel[[i]] %>% remove_empty("rows")
}

You asked for a for-loop, but actually this can be done just by using an lapply statement, so I provided both.

Hope this helps,
PJ