【问题标题】:openxlsx writing if formula from R to excel如果公式从 R 到 excel,openxlsx 写作
【发布时间】:2018-05-04 16:55:19
【问题描述】:

我正在尝试从 R 导出到 excel 具有两列的数据框,我想用 excel if 公式填充这些列,以便用户稍后可以更改阈值。我的问题是如何将像以下 IF(C2>4; "YES";"NO") 的公式导出到新列的每个单元格到 Excel 中。

R 代码:

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

我尝试创建 excel 公式的方式不起作用。该脚本在我将列声明为公式的步骤失败。第二种创建单独向量并将它们导出到工作簿的方法也不起作用。

我该如何解决这个问题?

【问题讨论】:

  • 问题是什么?
  • 我尝试创建 excel 公式的方式不起作用。该脚本在我将列声明为公式的步骤失败。第二种创建单独向量并将它们导出到工作簿的方法也不起作用。

标签: r excel excel-formula r-xlsx openxlsx


【解决方案1】:

您的 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多