首页 > 解决方案 > 在 R 函数中向量化 FOR 循环

问题描述

我在下面有这段代码,它与虹膜数据完美配合,但是如果你用更大的数据集加载它,相同的代码将需要很长时间才能运行。我注意到问题是for循环。我怎样才能 vectozize 循环并使代码更快。

rm(列表=对象(全部=真))

today <- Sys.Date()
format(today, format="%d-%b-%Y")

#LIBRARIES
library(openxlsx)
library(readxl)
library(lubridate)
library(zoo)
library(stringr)
library(data.table)


#READ IN DATA SETS
DATA <- iris


#CREATE A NEW EXCEL WORKBOOK
wb <- createWorkbook()
modifyBaseFont(wb, fontSize = 10, fontColour = "black", fontName = "Book 
Antiqua")

#ADD WORKSHEET
addWorksheet(wb,"IRIS DATA",zoom = 92,tabColour = "red2")


#WRITE DATA FUNCTION
WRITEDATAFUNCTION <- function(data,sheet,stRow,stCol){
writeData(wb, paste0(sheet), data,startRow = stRow, startCol = stCol)  
writeDataTable(wb, paste0(sheet), data, startRow = stRow, startCol = 
stCol,tableStyle = 
"none",withFilter = FALSE)

style1 <- createStyle(halign = "CENTER",numFmt ="#,###",fontColour = 
"blue") 

**for(i in stRow:(stRow+nrow(data))){
addStyle(wb, paste0(sheet), style1, rows = i, cols=(stCol): 
(stCol+ncol(data[i,])), gridExpand = TRUE, 
 stack = TRUE)
}**

}


 WRITEDATAFUNCTION(DATA,"IRIS DATA",1,1)

saveWorkbook(wb, file = paste("BBBBBB","-",Sys.Date(),".xlsx"), overwrite = 
TRUE)

标签: r

解决方案


真的不需要循环。我已经将脚本修改如下,现在速度更快了。

today <- Sys.Date()
format(today, format="%d-%b-%Y")

#LIBRARIES
library(openxlsx)
library(readxl)
library(lubridate)
library(zoo)
library(stringr)
library(data.table)


#READ IN DATA SETS
 DATA <- iris


#CREATE A NEW EXCEL WORKBOOK
wb <- createWorkbook()
modifyBaseFont(wb, fontSize = 10, fontColour = "black", fontName = "Book 
Antiqua")

#ADD WORKSHEET
addWorksheet(wb,"IRIS DATA",zoom = 92,tabColour = "red2")


#WRITE DATA FUNCTION
WRITEDATAFUNCTION <- function(data,sheet,stRow,stCol){
writeData(wb, paste0(sheet), data,startRow = stRow, startCol = stCol)  
writeDataTable(wb, paste0(sheet), data, startRow = stRow, startCol = 
stCol,tableStyle = 
"none",withFilter = FALSE)

style1 <- createStyle(halign = "CENTER",numFmt ="#,###",fontColour = 
"blue") 
addStyle(wb, paste0(sheet), style1, rows = stRow:(stRow+nrow(data)), cols=(stCol): 
(stCol+ncol(data[i,])), gridExpand = TRUE, stack = TRUE)
}


WRITEDATAFUNCTION(DATA,"IRIS DATA",1,1)

saveWorkbook(wb, file = paste("BBBBBB","-",Sys.Date(),".xlsx"), overwrite = 
TRUE)

推荐阅读