简体   繁体   English

在 R FUNCTION 中为循环矢量化

[英]VECTORIZING FOR LOOP IN AN R FUNCTION

I have this code below that works perfectly well with the Iris Data, however the same code will take ages to run if you load it with a bigger data set.我在下面有这段代码,它与虹膜数据完美配合,但是如果你用更大的数据集加载它,相同的代码将需要很长时间才能运行。 i notice the problem is the for loop.我注意到问题是for循环。 How can I vectozize the loop and make the code faster.我怎样才能 vectozize 循环并使代码更快。

rm(list=objects(all=TRUE)) 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)

There was really no need for a loop.真的不需要循环。 I've revised the script as below and it is much faster now.我已经将脚本修改如下,现在速度更快了。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM