0

I am trying to create a new column within a datatable that will essentially act like a "Text to Columns" in Excel. But when I try, it just writes the formula in a column outside the table and returns a #REF!.

I am having trouble finding Q/A for openxlsx2, has anyone figured this out?

NOTE: I have tried to "pre-add" a column and fill that too, but it also did not work.

Here is an example of my problem:

library(dplyr)
library(tidyr)
library(openxlsx2)

mtcars_model <- mtcars %>%
  mutate(model = rownames(.)
         # ,
         # formula = NA
         )

temp_path <- file.path(tempdir(), paste0(format(Sys.time(), format = "%m-%d-%H%M-%S"),"_mtcars_openxlsx2_test.xlsx"))

wb <- wb_workbook() %>%
  wb_add_worksheet("Data") 

wb$add_data_table(sheet = "Data",
                  x = mtcars_model,
                  tableName = "mtcars")

wb$add_formula(sheet = "Data",
               x = '=LEFT(mtcars[@model],FIND(" ",mtcars[@model],1))',
               array = TRUE,
               startRow = 2:(nrow(mtcars_model) + 1),
               startCol = which(colnames(mtcars_model) == "model" , arr.ind = TRUE) + 5)

wb$save(path = temp_path)

shell.exec(temp_path)
  

2
  • if you are using R, manipulate the data in R, create the newq variables in R. Ensure everything looks fine. Save the results as xlsx wooksheet/book. If you want all manipulations to be done in excel, i would advice to use excel and VBA Commented Sep 13, 2023 at 18:55
  • thank but i was trying to automate an interactive workbook Commented Sep 13, 2023 at 19:15

1 Answer 1

0

The documentation is hiding in plain sight.

library(openxlsx2)

mtcars_model <- mtcars %>%
  dplyr::mutate(model = rownames(.)
)

temp_path <- file.path(tempdir(), paste0(format(Sys.time(), format = "%m-%d-%H%M-%S"),"_mtcars_openxlsx2_test.xlsx"))

mtcars_model$formula <- 'LEFT(mtcars[[#This Row], [model]],FIND(" ", mtcars[[#This Row], [model]],1))'
class(mtcars_model$formula) <- "formula"

wb <- wb_workbook() %>%
  wb_add_worksheet("Data") %>% 
  wb_add_data_table(x = mtcars_model, table_name = "mtcars")

if (interactive()) wb$open()
Sign up to request clarification or add additional context in comments.

3 Comments

thank you this worked! and thanks for the link i never got that as a result when googled. however in your code, the "table_name" argument is actually "tableName" in case you want to edit your response.
Thanks, but we switched to snake case in release 1.0, camel case is still supported though no longer the default.
OH. lol im using 0.7.1.... time to update. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.