加快我在 R 中的嵌套 for 循环并在 excel 中存储一个超大数据帧超出其限制
Speed up my nested for loop in R and storing a very large data frame in excel beyond its limits
我花了整整 36 小时甚至更长时间才努力使用 R 中的以下代码行创建数据框。任何使此代码更快的建议都会受到赞赏。然而,到最后,我需要将这个数据框存储在一个 excel 文件中,但我注意到这个特定代码需要超过 3 亿行,超过了典型的 excel sheet 长度.我期待获得帮助,将其存储在 excel(或记事本)文件中以备将来使用。
library(writexl)
team_b <- 10:120
individual_b <- 1:84
team_s <- 1:250
individual_s <- 1:150
d <- data.frame()
for (i in team_b) {
for (j in individual_b) {
for (k in team_s) {
for (l in individual_s) {
sc <- l/k
bu <- j/i
sr <- l/j
pi <- sc/bu
if(bu>0.7||sc>0.7||sr>6){
c = "unrealistic"
}
else{
c = "realistic"
}
d <- rbind(d, data.frame(i,j,k,l,sc,bu,sr,pi,c))
}
}
}
}
colnames(d) <- c("T_b", "I_b", "T_s", "I_s", "BU", "SC", "SR", "PI", "Comment")
#View(d)
write_xlsx(d, "d.xlsx")
library(data.table)
d <- CJ(team_b, individual_b, team_s, individual_s) # generate all combinations
setnames(d, c('i', 'j', 'k', 'l'))
d[, sc := l/k]
d[, bu := j/i]
d[, sr := l/j]
d[, pi := sc/bu]
d[, c := ifelse(bu > 0.7 | sc > 0.7 | sr > 6, "unrealistic", "realistic")]
我花了整整 36 小时甚至更长时间才努力使用 R 中的以下代码行创建数据框。任何使此代码更快的建议都会受到赞赏。然而,到最后,我需要将这个数据框存储在一个 excel 文件中,但我注意到这个特定代码需要超过 3 亿行,超过了典型的 excel sheet 长度.我期待获得帮助,将其存储在 excel(或记事本)文件中以备将来使用。
library(writexl)
team_b <- 10:120
individual_b <- 1:84
team_s <- 1:250
individual_s <- 1:150
d <- data.frame()
for (i in team_b) {
for (j in individual_b) {
for (k in team_s) {
for (l in individual_s) {
sc <- l/k
bu <- j/i
sr <- l/j
pi <- sc/bu
if(bu>0.7||sc>0.7||sr>6){
c = "unrealistic"
}
else{
c = "realistic"
}
d <- rbind(d, data.frame(i,j,k,l,sc,bu,sr,pi,c))
}
}
}
}
colnames(d) <- c("T_b", "I_b", "T_s", "I_s", "BU", "SC", "SR", "PI", "Comment")
#View(d)
write_xlsx(d, "d.xlsx")
library(data.table)
d <- CJ(team_b, individual_b, team_s, individual_s) # generate all combinations
setnames(d, c('i', 'j', 'k', 'l'))
d[, sc := l/k]
d[, bu := j/i]
d[, sr := l/j]
d[, pi := sc/bu]
d[, c := ifelse(bu > 0.7 | sc > 0.7 | sr > 6, "unrealistic", "realistic")]