如何在 R 中的 xlsx 包中使用 setCellFormula 中的行和列变量?

How can use variables for the row and columns in setCellFormula in the xlsx package in R?

我正在尝试在现有 Excel 文档的单元格中创建公式。我可以很容易地这样做:

#Load workbook
  wb<-loadWorkbook('test.xlsx') #Let this be any xlsx document with borders on cell B1 of Sheet2
#Get tab 
  tab=wb$getSheet('Sheet2')  
  rows<-getRows(tab)
  cells <- getCells(rows)
#You can set a formula in a cell
  cells$'1.2'$setCellFormula("A1") #Cell B1 will now have the formula "=A1"
  cells$`1.2`
#Save the workbook with a new name
  saveWorkbook(wb,"test2.xlsx")

我想做的是能够根据我事先计算的变量轻松修改单元格的地址。一些事情,例如:

#You can set a formula in a cell
  r<-1
  c<-2
  cells$'r.c'$setCellFormula("A1") #Cell B1 will now have the formula "=A1"
  cells$`r.c`

我试过这样的事情:

eval(paste0("cells$`",r,".",c,"'$setCellFormula('A1')"))

但我得到的只是:

[1] "cells$`2.2'$setCellFormula('A1')"

有谁知道如何用变量轻松替换行号和列号? 感谢您的帮助!

您应该 parseeval 对其进行修改之前 parse 文本:

eval(parse(text=paste0("cells$'",r,".",c,"'$setCellFormula('A1')")))