openxlsx Excel 一行中的公式,如何为每一列动态创建公式

openxlsx Excel formulae in a row, how to create formula dynamically for each column

我的目标

我有一个包含多个列的数据集,存储在 excel 文件中。对于每一列,我需要在数据集的一侧插入统计公式。应动态创建公式。

为了示例,让我们创建一个 3 列 10 行的示例,以便任何人都可以遵循。

wb <- createWorkbook(title = "simulation")
addWorksheet(wb, "stats") # create a sheet
writeData(wb, "stats", data.frame(A=c(1:10)*pi, B=1/c(6:15), C=sqrt(11:20))) # store the example data frame
saveWorkbook(wb, "formula_example.xlsx", overwrite = TRUE) # save the file

数据集现在看起来是这样的: data set

我想在 excel 数据集的左侧插入一组公式,比如 E 列。 例如,我需要每一列的平均值和标准偏差。

我试过方法一:

根据 R 文档,我可以使用 writeFormula 方法。但这会将我的公式放在一列中,而我需要它们排成一行!! https://www.rdocumentation.org/packages/openxlsx/versions/4.1.5/topics/writeFormula

wb <- loadWorkbook(xlsxFile = "formula_example.xlsx") # load the file
v1 <- c("AVERAGE(A2:A11)", "AVERAGE(B2:B11)", "AVERAGE(C2:C11)") # the vector of formulae
writeFormula(wb, sheet = "stats", x = v1, startCol = "E", startRow = 2) # column E and row 2
saveWorkbook(wb, "formula_example.xlsx", overwrite = TRUE) # save the file

方法2我试过了

文档中有 writeData 方法,您必须在其中重新class 单元格作为公式。如果我创建一个内部包含动态公式的数据框并将其存储到 excel,也许我可以让它工作。

df <- data.frame() # initialize as empty data frame
df <- rbind(
  df, # append the formula rows below and create the column names with the method int2col
  sapply(1:3, function(i){paste0("AVERAGE(",int2col(i),"2:",int2col(i),"11)")})
)

df <- rbind(
  df, # do the same for standard deviation
  sapply(1:5, function(i){paste0("STDEV.S(",int2col(i),"2:",int2col(i),"11)")})
)
colnames(df) <- c("A","B","C") # set sensible names

现在数据框 df 看起来像这样:

> df
                A               B               C
1 AVERAGE(A2:A11) AVERAGE(B2:B11) AVERAGE(C2:C11)
2 STDEV.S(A2:A11) STDEV.S(B2:B11) STDEV.S(C2:C11)

现在,我将其存储到 excel:

class(df[1,]) <- c(class(df[1,]), "formula") # reclass as formula (not sure that this one is correct!!)
class(df[2,]) <- c(class(df[2,]), "formula") # in fact, it doesn't seem to work

writeData(wb, sheet = "stats", x = df, startCol = "E", startRow = 1) # set where to put the stats
saveWorkbook(wb, "formula_example.xlsx", overwrite = TRUE) # save the file

它确实作为行存储到 excel 中,但作为显式文本而不是公式!!结果如下所示: resulting data set

您可以使用 lapply 将要写入的公式传递给 Excel sheet。 请注意,由于某种原因,如果 Excel 公式中有 .,它似乎无法正确识别该公式,因此在此示例中已将其替换为 STDEV。

wb <- createWorkbook(title = "simulation")
addWorksheet(wb, "stats") 

# Data
writeData(wb, "stats", data.frame(A=c(1:10)*pi, B=1/c(6:15), C=sqrt(11:20)))

# Formula Vector
v1 <- c("AVERAGE(A2:A11)", "AVERAGE(B2:B11)", "AVERAGE(C2:C11)")
v2 <- c("STDEV(A2:A11)", "STDEV(B2:B11)", "STDEV(C2:C11)") 

# Columns where you want to store formulas
column1 <- c("E", "F", "G")

# write formula AVERAGE & STDEV 
lapply(1:length(column1), FUN = function(x) writeFormula(wb, "stats", x = v1[x], startCol = column1[x], startRow = 2))
lapply(1:length(column1), FUN = function(x) writeFormula(wb, "stats", x = v2[x], startCol = column1[x], startRow = 3))

saveWorkbook(wb, "formula_example83.xlsx", overwrite = TRUE)