将单元格中包含公式的 excel 文件读入 R

Read excel file with formulas in cells into R

我试图将 excel 电子表格读入 R 数据框。但是,某些列具有公式或链接到其他外部电子表格。每当我将电子表格读入 R 时,总会有很多单元格变成 NA。有什么好的方法可以解决这个问题,让我可以得到这些单元格的原始值吗?

我用来导入的R脚本如下:

options(java.parameters = "-Xmx8g")
library(XLConnect)
# Step 1 import the "raw" tab
path_cost = "..."
wb = loadWorkbook(...)
raw = readWorksheet(wb, sheet = '...', header = TRUE, useCachedValues = FALSE)

更新:readxl 包中的 read_excel 看起来是更好的解决方案。它非常快(我在评论中提到的 1400 x 6 文件中为 0.14 秒)并且它在导入之前评估公式。它不使用 java,因此无需设置任何 java 选项。

 # sheet can be a string (name of sheet) or integer (position of sheet)
 raw = read_excel(file, sheet=sheet)

有关更多信息和示例,请参阅 the short vignette

原始答案: 尝试 xlsx 包中的 read.xlsx。帮助文件暗示默认情况下它会在导入之前评估公式(请参阅 keepFormulas 参数)。我在一个小测试文件上检查了这个,它对我有用。公式结果已正确导入,包括依赖于同一工作簿中其他 sheet 的公式和依赖于同一目录中其他工作簿的公式。

一个警告:如果外部链接 sheet 自您上次更新您正在读入 R 的文件上的链接以来发生了变化,那么任何读入 R 的依赖于外部链接的值都将是旧值,不是最新值。

你的代码是:

library(xlsx)

options(java.parameters = "-Xmx8g") # xlsx also uses java

# Replace file and sheetName with appropriate values for your file
# keepFormulas=FALSE and header=TRUE are the defaults. I added them only for illustration.
raw = read.xlsx(file, sheetName=sheetName, header=TRUE, keepFormulas=FALSE)