Это итеративное решение, которое не может гарантировать, что всем назначен пакет из 6 элементов:
df <- structure(list(ProductID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), RealQuantity = c(5, 1, 1, 5, 5, 1, 3, 3, 3, 3, 3, 3, 3, 5, 3, 3, 3, 3, 3, 3), RealWeigth = c(0.296, 0.064, 0.061, 0.297, 0.298, 0.058, 0.172, 0.172, 0.177, 0.1695, 0.179, 0.18, 0.175, 0.301, 0.181, 0.178, 0.161, 0.178, 0.1775, 0.183), PickingDate = structure(c(17526, 17536, 17536, 17541, 17544, 17547, 17554, 17554, 17554, 17555, 17556, 17556, 17557, 17557, 17557, 17557, 17558, 17561, 17562, 17562), class = "Date")), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))
# for portion of data.frame with RealQuantity < 6:
df$group <- NA
df <- df[order(df$RealQuantity, decreasing=TRUE),]
gi <- 0
groupsize <- 0
while (TRUE) {
gi <- gi + 1
# find biggest, non-assigned row:
i <- min(which(is.na(df$group)))
if (is.infinite(i)) # nothing found; which would return a zero-length vector. But min(integer(0)) returns Inf.
break
groupsize <- df$RealQuantity[i]
df$group[i] <- gi
# find next line whos combined quantity might fit within "6":
while (TRUE) {
j <- min(which(is.na(df$group) & df$RealQuantity + groupsize <= 6))
if (is.infinite(j)) # nothing found
break
groupsize <- groupsize + df$RealQuantity[j]
df$group[j] <- gi
if (groupsize >= 6)
break
}
}
library(dplyr)
df %>% group_by(group) %>% summarise_at(vars(RealQuantity, RealWeigth), funs(sum))
или более подробная информация:
df %>% group_by(group) %>% summarise(combined=paste(RealQuantity, collapse=', '), RealQuantity=sum(RealQuantity), RealWeigth=sum(RealWeigth), Firstdate=min(PickingDate))