writexl::write_xlsx() dynamic sheet name

I am trying to write an excel file and dynamically update its sheet name using writexl::write_xlsx().

In the code below, my intention is to name the sheet as "my_sheet_has_32_rows" using the vector my_sheet_name, but the code names the sheet as "my_sheet_name".

library(writexl)
#> Warning: package 'writexl' was built under R version 4.1.2
# Data
df <- mtcars
n_rows <- (nrow(df))

my_sheet_name <- paste0("my_sheet_has_", n_rows, "_rows")
my_sheet_name
#> [1] "my_sheet_has_32_rows"

writexl::write_xlsx(list(my_sheet_name = df),
                    "data/my_file_name.xlsx")

Created on 2022-01-05 by the reprex package (v2.0.1)

You can use setNames()

write_xlsx(setNames(list(df), my_sheet_name), "data/my_file_name.xlsx")
1 Like

@andresrcs many thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.