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)
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()