openxlsx::writeFormula rowwise - is there an efficient way to do this?

Viewed 658

openxlsx functions to write formula seem to add formula columnwise only.

Is there an efficient way to write formula rowwise?

Working through a reproducible example to illustrate the issue:

df <- data.frame(a = 1:3,
                 b = 4:6,
                 c = 7:9)

# create workbook, worksheet and write data to worksheet
wb <- createWorkbook()
addWorksheet(wb, "Sheet 1")
writeData(wb, "Sheet 1", x = df)

#  formula to be added rowwise to cells A5:C5
f <- c("SUM(A2:A4)", "SUM(B2:B4)", "SUM(C2:C4)")

# Using the openxlsx function results in columnwise addition of the formula vector: 
writeFormula(wb, sheet = 1, x = f, startCol = 1, startRow = 5)

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

This results in:

enter image description here

writeFormula rowwise

The naive approach is to add each formula individually, maybe OK for small data sets.

writeFormula(wb, sheet = 1, x = "SUM(A2:A4)", startCol = 1, startRow = 5)
writeFormula(wb, sheet = 1, x = "SUM(B2:B4)", startCol = 2, startRow = 5)
writeFormula(wb, sheet = 1, x = "SUM(B2:B4)", startCol = 3, startRow = 5)

This provides what I want but is not a viable approach for hundreds of columns.

Using purrr::pwalk this can be wrapped up in a function, which is an improvement:

formula_inputs <- list(formula = f,
                       start_col = 1:3,
                       start_row = rep(5, 3))

purrr::pwalk(formula_inputs, function(formula, start_col, start_row) writeFormula(wb, sheet = 1, x = formula, startCol = start_col, startRow = start_row))

Either way this does what is required:

enter image description here

My question: is there a better way to do this? or might it be an enhancement to openxlsx?

In my real case I have 100 variables for 10 data frames in a list each requiring multiple (10) rowwise formula to build up to a total. In all about 10,000 formula need to be written, this takes several minutes; so any ideas on how to speed up the process would be welcome.

Note: openxlsx's alternative approach using writeData for vectors of class 'formula' also add the vectors as columns; when I try to transpose the vectors into rows the formula class is lost.

0 Answers
Related