子集数据并将这些数据写入单独的Excel模板的For循环

时间:2019-02-21 16:24:11

标签: r excel loops subset xlconnect

基本上,我有一个数据集,其中包含针对约100种不同设施的数千行数据,并通过其“设施ID”进行区分。对于这些工具中的每一个,我都试图从该总体数据中自动填充一个单独的Excel工作簿(因此为每个工具的数据创建一个单独的工作簿)。我能够使代码在循环内运行而不会出现问题(这是我根据数据制作Excel工作簿的部分)。我只是似乎看不到循环本身在做什么。任何反馈都将受到欢迎!为了方便起见,我创建了一个非常简化的数据和代码片段。

请参见照片以获取示例数据表Transfers_ALL

> for (i in 1:length(uniq)){
  Transfers <- subset(data, Transfers_ALL$Facility_ID == uniq[i])

  #making empty matrix
  m <- (data.frame(matrix('', nrow = 60,ncol = 60), stringsAsFactors=FALSE)) 

  # places values in specific cells in the new empty matrix. 
  m[1:(1+length(Transfers$Facility_ID)-1),3]<- Transfers$Facility_ID
  m[1:(1+length(Transfers$Col1)-1),8] <- Transfers$Col1 # row#, column#

  ##' Puts the data from the new filled matrix into a pre-formatted excel workbook template. 
  wb <- XLConnect::loadWorkbook("test.xlsx", create=TRUE)
  setStyleAction(wb,XLC$"STYLE_ACTION.NONE")
  XLConnect::writeWorksheet(wb,m,"Sheet1",startRow=13,startCol=1,header=F)

  #Saves the new workbook for each Facility (or at least thats what I'm 
  #trying to do)       
  XLConnect::saveWorkbook(wb, name=paste("mywb",uniq[i],".xlsx",sep=""))
}

1 个答案:

答案 0 :(得分:1)

如果我理解这个问题,则可以执行以下操作。

首先,创建一个数据集,因为您尚未以易于复制和粘贴的形式发布数据集。

set.seed(12345)    # Make the results reproducible
Facility_ID <- rep(sprintf("%s%04d", c("P", "P", "W"), c(123, 345, 678)), each = 3)
Col1 <- sample(c("metal", "concrete", "mixed", "c and d", "municipal"), 9, TRUE)
Col2 <- sample(10, 9, TRUE)
Col3 <- sample(c("yes", "no"), 9, TRUE)

Transfers_ALL <- data.frame(Facility_ID, Col1, Col2, Col3)

现在输入代码。

write_sp_ALL <- function(DF, df_name){
  m <- as.data.frame(matrix('', nrow = 60, ncol = 60), stringsAsFactors = FALSE)

  nr <- nrow(DF)
  # places values in specific cells in the new empty matrix. 
  m[seq_len(nr), 3] <- as.character(DF[["Facility_ID"]])
  m[seq_len(nr), 8] <- as.character(DF[["Col1"]])

  file_name <- paste0("mywb", df_name, ".xlsx")  
  XLConnect::writeWorksheetToFile(file_name, m, sheet = "Sheet1", 
                            startRow = 13, startCol = 1, 
                            header = FALSE)

}

sp_ALL <- split(Transfers_ALL, Transfers_ALL[[1]])
nms <- names(sp_ALL)
lapply(seq_along(sp_ALL), function(i) 
  write_sp_ALL(sp_ALL[[i]], nms[i]))