I have many functions which create a list of tables. All the tables have different demographies.
I am looking for a function to dynamically save the list of tables in xlsx file one by one.
library(expss)
library(dplyr)
library(purrr)
df <- mtcars
df1 <- subset(df, vs==1)
df2 <- subset(df, am==1)
df3 <- subset(df, gear==3)
df_list <- list(df1,df2,df3)
banner <- c("T1","T2","T3")
sub_fun<-function(db,var,var_name){
var = rlang::parse_expr(var)
df1<- db %>% filter(!is.na(!!var)) %>% summarise(
Median =quantile(!!var, type=6, probs = seq(0, 1, 0.25), na.rm=TRUE)[3],
Mean = mean(!! var, na.rm=TRUE),
N = sum(!is.na(!!var)))
df<- df1 %>% mutate(" "=!!var_name,
Median = Median,
Mean = Mean,)
df <- df %>% select(" ",everything(),N)
df
}
func1<-function(db,list_var,var_name_list,....){
table_list1<-list()
for (d in 1:length(df_list)) {
table_list<-list()
for (i in 1:length(list_var)) {
table_list[[i]]<-sub_fun(db, list_var[i],var_name_list[i])
t1 <- do.call(rbind,table_list)
}
colnames(t1)[1] <- banner[[d]]
t1 <- t1 %>%
add_row() %>%
mutate_all(~replace(., is.na(.), ""))
table_list1[[d]] <- t1
}
names(table_list1) <- banner
Map(cbind, table_list1, SampleID = names(table_list1))
colnames <- c("name","Median","Mean", "N")
for (i in seq_along(table_list1)){
colnames(table_list1[[i]]) <- colnames
}
t2 <- do.call(rbind,table_list1)
t2
}
t1<- func1(db=df,list_var=c("cyl","disp","hp"),var_name_list=c("klick","Nemar","Wingo"))
t2 = mtcars %>%
cross_cpct(
cell_vars = list(cyl, gear),
col_vars = list(total(), am, vs)
) %>%
set_caption("Table 1")
tbls <- c(t1,t2)
startRows <- c(0, cumsum(2 + sapply(tbls, nrow)[-length(tbls)])) + 1
fn <- tempfile(fileext = "xlsx")
wb <- createWorkbook()
addWorksheet(wb, "tbls")
mapply(function(tbl, startRow) writeData(wb, "tbls", x = tbl, startRow = startRow), tbls, startRows)
saveWorkbook(wb, fn, overwrite = TRUE) %>% file.show(.)
I have tried this way but it doesn't work. Is there a solution for this?
actually its not saving tables in xlsx files , i am getting many errors meanwhile trying this approach
it should save tables in xlsx files like below