Home > Net >  How to use lapply to skimr:: skim multiple data frames then export them to Excel?
How to use lapply to skimr:: skim multiple data frames then export them to Excel?

Time:07-28

I have 2 data frames(more in real life). My goal is to apply the skim function then export them as excel to a folder. They would also have different Excel file names.

df1 <- data.frame(x = rep(3, 5), y = seq(1, 5, 1), ID = letters[1:5])

df2 <- data.frame(x = rep(5, 5), y = seq(2, 6, 1), ID = letters[6:10])

I need the short way to accomplish the below:

for df1:

df1_summary<-skim(df1)

df1_summary<-as.data.frame(df1_summary)

write_xlsx(df1_summary,"df1_summary.xlsx")

for df2:

df2_summary<-skim(df2)

df2_summary<as.data.frame(df2_summary)

write_xlsx(df2_summary,"df2_summary.xlsx")

So far I know, df.list<-list(df1, df2)

lapply(df.list, function(x) ...

I have many more than 2 data frames for this task in real life. Any help to shorten the process would helpful!

CodePudding user response:

We can apply the function after placing the datasets in a list

library(skimr)
lst1 <- lapply(list(df1, df2), function(x) {

    dat <-  as.data.frame(skim(x)) 
    })

names(lst1) <- c('df1_summary', 'df2_summary')
Map(function(x, y) write_xlsx(x, paste0(y, ".xlsx")), lst1, names(lst1))
  • Related