openxlsx 中的自定义列名称

Custom column names in openxlsx

我将使用 openxlsx 生成报告。

我有一个数据框,其中的列名对最终用户不友好。所以我想生成一个带有自定义列的 excel 文件。我已经想出如何使用 colNames = FALSE 忽略列名,但是添加我需要的名称的最佳方法是什么?

report <- createWorkbook('report.xlsx')

addWorksheet(report, 'test')

# how to add column names

writeData(report, sheet = 1, df, colNames = FALSE)

saveWorkbook(report, 'report.xlsx', overwrite = TRUE)

重命名列名可能比忽略它们更好。例如:

library(tidyverse)
library(openxlsx)

wb = createWorkbook()

sht = addWorksheet(wb, "data")

mtcars %>%
  rename(Cylinders = cyl, 
         `Miles per Gallon` = mpg) %>%
  writeData(wb, sht, .)

saveWorkbook(wb, "myworkbook.xlsx")

如果您要生成这样的定期报告,您可以创建一个包含 new-name/old-name 对的向量以进行重命名。例如:

# Renaming vector
rename.vec = c("Cylinders"="cyl",
               "Miles per Gallon"="mpg",
               "Displacement"="disp")

# Example of renaming using the vector we just created
mtcars %>% 
  rename(!!!rename.vec) %>% 
  head
                  Miles per Gallon Cylinders Displacement  hp drat    wt  qsec vs am
Mazda RX4                     21.0         6          160 110 3.90 2.620 16.46  0  1
Mazda RX4 Wag                 21.0         6          160 110 3.90 2.875 17.02  0  1
Datsun 710                    22.8         4          108  93 3.85 2.320 18.61  1  1
Hornet 4 Drive                21.4         6          258 110 3.08 3.215 19.44  1  0
Hornet Sportabout             18.7         8          360 175 3.15 3.440 17.02  0  0
Valiant                       18.1         6          225 105 2.76 3.460 20.22  1  0
                  gear carb
Mazda RX4            4    4
Mazda RX4 Wag        4    4
Datsun 710           4    1
Hornet 4 Drive       3    1
Hornet Sportabout    3    2
Valiant              3    1
# Write data to a worksheet, renaming columns on the fly
writeData(wb, sht, mtcars %>% rename(!!!rename.vec))