如何将 R 中数据框中的数据附加到已存在的 Excel sheet

How do I append data from a data frame in R to an Excel sheet that already exists

我在 R 中创建了数十个数据框,并想将它们全部附加到 sheet 文件中的一个 sheet。

这是我为了寻找答案而查看过的两个页面(我没有 10 个声誉,所以我无法粘贴我访问过的所有四个网页网址):

Write data to Excel file using R package xlsx 作者说:"You can also add the dataframes to a particular starting place in the sheet using the startRow and startCol arguments to the addDataFrame function." 这是建议的代码:

workbook.sheets workbook.test addDataFrame(x = sample.dataframe, sheet = workbook.test,
   row.names = FALSE, startColumn = 4) # write data to sheet starting on line 1, column 4
saveWorkbook(workbook.sheets, "test.excelfile.xlsx") # and of course you need to save it.

根据这个建议,这是我在 RStudio 中的尝试:

addDataFrame(df_fl1, sheet = "AllData2.xlsx", startRow = 712)

这是 R 的输出: sheet$getWorkbook 中的错误:$ 运算符对原子向量无效

我也试过这个页面:

Tutorial on Reading and Importing Excel Files into R "If, however, you want to write the data frame to a file that already exists, you can execute the following command:"

write.xlsx(df, 
           "<name and extension of your existing file>", 
           sheetName="Data Frame"
           append=TRUE)
write.xlsx(df_fl3, "AllData2.xlsx", sheetName="Salinity1", append=TRUE)

我试过这段代码,它覆盖了 sheet 中已有的数据。如何将数据帧中的数据附加到 Excel sheet?

附加到现有的 Excel 工作表有点麻烦。相反,将所有 Excel 数据文件读入 R,在 R 中组合它们,然后将单个组合数据帧写入新的 Excel 文件(如果不这样做,则写入 csv 文件)需要数据在 Excel 工作簿中)。请参阅下面的代码,了解简单方法和困难方法。

简单方法:完成R中的所有工作并在最后保存一个组合数据框

例如,如果所有 Excel 数据文件都在当前工作目录中,并且每个 Excel 文件中的第一个工作表包含数据,您可以执行以下操作:

library(xlsx)

# Get file names
file.names = list.files(pattern="xlsx$")

# Read them into a list
df.list = lapply(file.names, read.xlsx, sheetIndex=1, header=TRUE)

然后将它们组合成一个数据帧并写入磁盘:

df = do.call(rbind, df.list)

write.xlsx(df, "combinedData.xlsx", sheetName="data", row.names=FALSE)

困难方式:将连续的数据帧附加到 pre-existing Excel 工作表

创建我们要写入的数据帧列表 Excel(如上所述,在您的实际用例中,您会将数据文件读入 R 中的列表)。我们将在此处使用 built-in iris 数据框进行说明:

df.list = split(iris, iris$Species)

要将每个数据框写入单个 Excel 工作表,首先,创建一个 Excel 工作簿和我们要写入数据的工作表:

wb = createWorkbook()
sheet = createSheet(wb, "data")

# Add the first data frame
addDataFrame(df.list[[1]], sheet=sheet, row.names=FALSE, startRow=1)

现在使用循环附加所有剩余的数据帧。每次递增startRow,以便将下一个数据帧写入正确的位置。

startRow = nrow(df.list[[1]]) + 2    

for (i in 2:length(df.list)) {

  addDataFrame(df.list[[i]], sheet=sheet, row.names=FALSE, col.names=FALSE, 
               startRow=startRow)

  startRow = startRow + nrow(df.list[[i]])

  }

保存工作簿:

saveWorkbook(wb, "combinedData.xlsx")

addDataFrame 如果您想在 Excel 工作表的各个部分布置各种汇总表并使其看起来很适合展示,那么

addDataFrame 很有用。但是,如果您只是将原始数据合并到一个数据文件中,我认为在 R 中完成所有工作然后将合并的数据框写入 Excel 工作表(或 csv 文件)要容易得多最后。

要解决您提到的原始错误:

Error in sheet$getWorkbook : $ operator is invalid for atomic vectors

你可以试试这个:

wb <- loadWorkbook("<name and extension of your existing file>")
addDataFrame(df,getSheets(wb)$<sheetname>, startRow = 712)
saveWorkbook(wb, <filename>)