Skip to content

Commit a34b462

Browse files
committed
avoid growing vector in create.sub.objects()
1 parent cdb9261 commit a34b462

1 file changed

Lines changed: 19 additions & 3 deletions

File tree

R/datplot_funs.R

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,18 +80,34 @@ get.weights <- function(DAT_min, DAT_max) {
8080

8181
# this could be optimizes, maybe with apply()? because it takes too long
8282
create.sub.objects <- function(df, stepsize) {
83-
result <- data.frame(NULL)
83+
84+
mean_year_index <- which(df[,4]-df[,3] < stepsize)
85+
86+
outputnr <- ceiling(sum(((abs(df[-mean_year_index,3]-df[-mean_year_index,4]))/stepsize)+1))
87+
outputnr <- outputnr+length(mean_year_index)
88+
89+
result <- as.data.frame(matrix(ncol = ncol(df)+1, nrow = outputnr))
90+
91+
colnames(result) <- c(colnames(df), "DAT_step")
8492
for (i in 1:nrow(df)) {
8593
sequence <- NULL
86-
sequence <- seq(df[i,3], df[i,4], by = stepsize)
94+
if ((df[i,4]-df[i,3]) < stepsize) {
95+
print(paste("stepsize is larger than the range of the closest dated object: ",
96+
df[i,1], " (Index = ", i, "). Using mean as year.", sep = ""))
97+
sequence <- (df[i,3]+df[i,4])/2
98+
} else {
99+
sequence <- seq(df[i,3], df[i,4], by = stepsize)
100+
}
87101
length <- length(sequence)
88102
for (step in sequence) {
89103
wip <- df[i,]
90104
wip$DAT_Step <- step
91105
wip$weight <- wip$weight / length(sequence)
92-
result <- rbind(result, wip)
106+
first_na <- match(NA, result$ID)
107+
result[first_na,] <- wip[,]
93108
}
94109
}
110+
result <- result[-c(match(NA, result$ID):nrow(result)), ]
95111
return(result)
96112
}
97113

0 commit comments

Comments
 (0)