Openxlsx writes if the formula from R to excel

I am trying to export from R to highlight a data frame with two columns that I want to populate with an excel formula so that the user can change the thresholds later. My question is how can I export a formula, for example, the following IF (C2> 4, "YES", "NO") to each cell of a new column in excel.

R code:

library(openxlsx)
library(dplyr)
export_df<-   mtcars %>% tibble::rownames_to_column(var="carname")

# Formulas in EXCEL IF(C>4; "YES";"NO") IF(E>100; "YES";"NO") 

export_df$many_cyl <- paste(paste(paste0(paste0("IF(C" ,seq(2,nrow(export_df)+1 ,1))," > 4")," 'Yes' ", sep=";")," 'No') ", sep=";")

export_df$fast_car <-  paste(paste(paste0(paste0("IF(E" ,seq(2,nrow(export_df)+1,1))," > 100")," 'Yes' ", sep=";")," 'No')", sep=";")

class(export_df$many_cyl) <- c(class(export_df$many_cyl), "formula")
class(export_df$fast_Car) <- c(class(export_df$fast_car), "formula")

openxlsx::addWorksheet(wb,sheetName ="mtcars" )
openxlsx::writeData(wb,"mtcars",export_df )
openxlsx::saveWorkbook(wb, "mtcars.xlsx")

The way I'm trying to create an excel formula does not work. The script fails at the stage where I declare the columns as formulas. The second way to create separate vectors and export them to a book also does not work.

How can i solve this?

+4
source share
1 answer

Excel . , , , . :

export_df$many_cyl <- paste(paste(paste0(paste0('=IF(C' ,seq(2,nrow(export_df)+1 ,1)),
                            ' > 4'),' "Yes" ', sep=','),' "No") ', sep=',')

export_df$fast_car <-  paste(paste(paste0(paste0('=IF(E' ,seq(2,nrow(export_df)+1,1)),
                             ' > 100'),' "Yes" ', sep=','),' "No")', sep=',')


wb <- createWorkbook()
addWorksheet(wb, "Sheet 1")
writeFormula(wb, sheet = "Sheet 1", x = export_df$many_cyl, startCol = 2, startRow = 1)
saveWorkbook(wb, "writeFormulaExample.xlsx", overwrite = TRUE)

enter image description here

+1

Source: https://habr.com/ru/post/1689608/


All Articles