0

我已经在文章“expss - R 中带有标签的表格”中阅读了这一点。使用提供的示例,我可以将 1 个表导出到 Excel。但我想导出很多表,同时运行。有人可以给我一些关于如何同时导出多个表的指示。问候

4

1 回答 1

0

最简单的方法是将所有表放在列表中。然后,您可以将此列表导出到 Excel。例子:

library(expss)
library(openxlsx)
data(mtcars)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (lb/1000)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)

banner = calc(mtcars, list(total(), am, vs))

library(comprehenr) # for 'to_list' function

list_of_tables = to_list(
    for(variable in mtcars){
        if(length(unique(variable))<7){
            cro_cpct(variable, banner) %>% significance_cpct()
        } else {
            # if number of unique values greater than seven we calculate mean
            cro_mean_sd_n(variable, banner) %>% significance_means()

        }    
    }
)

wb = createWorkbook()
sh = addWorksheet(wb, "Tables")

xl_write(list_of_tables, wb, sh)

saveWorkbook(wb, "report.xlsx", overwrite = TRUE)

如果您的表格非常不同并且您无法在循环中计算它们,那么您可以将它们一一放入列表中,例如:

list_of_tables[[1]] = tab1

...

list_of_tables[[10]] = tab10

更新。将打印的表格另外复制到名称为“输出”的列表的功能。

new_output = function(){
    output <<- list()
    print.etable <<- function(x, ...){
        output[[length(output) + 1]] <<- x
        expss:::print.etable(x, ...)
    }
    print.with_caption <<- function(x, ...){
        output[[length(output) + 1]] <<- x
        expss:::print.with_caption(x, ...)
    }
}

stop_output = function(){
    rm(print.etable, envir = .GlobalEnv)
    rm(print.with_caption, envir = .GlobalEnv)
}


new_output() # create empty list for output
banner = calc(mtcars, list(total(), am, vs))

# printed tables also will be added to 'output'
cro_cpct(mtcars$gear, banner)
cro_cpct(mtcars$carb, banner)

stop_output() # stop adding to list

wb = createWorkbook()
sh = addWorksheet(wb, "Tables")

xl_write(output, wb, sh)

saveWorkbook(wb, "report.xlsx", overwrite = TRUE)
于 2019-06-06T08:41:09.193 回答