如何在R表中创build一个行?

我试图用R(我所有的数据来自R和我需要组织在一个Excel文件中)我的每个Excel文件中添加一个标题。 为了做到这一点,我使用了'xlsx'包中的这个函数,我在这里find了 :

#++++++++++++++++++++++++ # Helper function to add titles #++++++++++++++++++++++++ # - sheet : sheet object to contain the title # - rowIndex : numeric value indicating the row to #contain the title # - title : the text to use as title # - titleStyle : style object to use for title xlsx.addTitle<-function(sheet, rowIndex, title, titleStyle){ rows <-createRow(sheet,rowIndex=rowIndex) sheetTitle <-createCell(rows, colIndex=1) setCellValue(sheetTitle[[1,1]], title) setCellStyle(sheetTitle[[1,1]], titleStyle) } 

程序是:1)创build一个新的行2)在这一行创build一个单元格来包含标题。 3)设置单元格值。

为了在每张纸上添加一个标题,我把这个函数放在一个循环中:

 # preparing for the loop wb <- loadWorkbook(file = "tmp_regioes.xlsx") sheets <- getSheets(wb) z <- length(titles) # creating the style SUB_TITLE_STYLE <- CellStyle(wb) + Font(wb, heightInPoints=14, isItalic=TRUE, isBold=FALSE) # loop for (i in (1:z)) { sheet <- sheets[[i]] # Add sub title xlsx.addTitle(sheet, rowIndex=1, title= paste0(titles[i]), titleStyle = SUB_TITLE_STYLE) } 

但它并不真正创造一个新的行; 相反,它会擦除​​我的第一行的内容,其中包含值(我的表的列名)。

只是澄清,文件“tmp_regioes.xlsx”是使用函数WriteXLS创build的,因为我需要在同一个文件上保存10个表; 例如,这个函数似乎没有保存第二行的表的选项。

如果有人能帮助我,我会很高兴。 谢谢大家。

我认为你有多种select:

  • 保存数据时,可以使用addDataFrame()函数中的参数startRow=2
  • 将标题放在第1行之前rows <-createRow(sheet,rowIndex=1)可以使用rows <-createRow(sheet,rowIndex=1)

下面的代码将从头开始提到一个示例xlsx文件。 希望这可以帮助!

 library(xlsx) df = data.frame(a=c(1,2,3),b=c(2,3,4)) titles = c( "A", "B","C") wb<- createWorkbook(type = "xlsx") sheets <- getSheets(wb) z <- length(titles) # creating the style SUB_TITLE_STYLE <- CellStyle(wb) + Font(wb, heightInPoints=14, isItalic=TRUE, isBold=FALSE) # loop for (i in (1:z)) { createSheet(wb, sheetName=paste0("Sheet",i)) sheets <- getSheets(wb) sheet <- sheets[[i]] # Add sub title addDataFrame(df, sheet, col.names = TRUE, row.names = FALSE, startRow = 1, startColumn = 1) rows <-createRow(sheet,rowIndex=1) xlsx.addTitle(sheet, rowIndex=1, title= paste0(titles[i]), titleStyle = SUB_TITLE_STYLE) } saveWorkbook(wb, "tmp.regioes.xlsx")