![](/img/trans.png)
[英]How can I handle whitespace when using `deparse(substitute))` (or an alternative)?
[英]Exporting multiple tibbles to XLSX — sheetName problem when using deparse(substitute())
我有15個要導出到單個XLSX工作簿的小標題,每個設置的sheetName與小標題對象的名稱相同。 要導出單個小標題,這很好用:
library(xlsx)
my_tibble1 %>%
write.xlsx("output_filename.xlsx",
sheetName = "my_tibble1",
append = TRUE)
但是,由於這些小標題足夠多,因此將每個小標題全部寫出來很費時間。 所以,我寫了一個函數:
output_expediter <- function(df, output_filename) {
write.xlsx(df,
output_filename,
sheetName = deparse(substitute(df)),
append = TRUE)
此函數成功將小標題寫入輸出工作簿中的新工作表,但sheetName始終為單個句點(“。”)。
用於小標題的所有變量名都限制為小寫字符和下划線,並且所有字符名的長度都不超過31個字符,因此我認為它們都不違反XLSX格式約定。 在R控制台中,運行:
deparse(substitute(my_tibble1))
如預期產生“ my_tibble1”。
為什么會這樣? 除了輸入每個工作表的名稱以外,還有其他可能的解決方法嗎?
一個選項是openxlsx
library(openxlsx)
library(tibble)
output_expediter <- function(df, output_filename) {
nm1 <- deparse(substitute(df))
wb <- createWorkbook()
addWorksheet(wb, sheetName = nm1)
writeData(wb, sheet= nm1, x = df)
saveWorkbook(wb =wb, file = output_filename, overwrite = TRUE)
}
file1 <- "hello.xlsx"
df1 <- tibble(col1 = 1:5, col2 = 6:10)
output_expediter(df1, file1)
-輸出
如果我們需要寫多個文件,
library(purrr)
wb1 <- createWorkbook()
output_expediter <- function(df, wb, nm1, output_filename) {
addWorksheet(wb, sheetName = nm1)
writeData(wb, sheet= nm1, x = df)
saveWorkbook(wb =wb, file = output_filename, overwrite = TRUE)
}
lst1 <- lst(df1= df1, df2= df1)
iwalk(lst1, ~ output_expediter(.x, wb = wb1, .y, file))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.