R语言BoxPacking包装箱解决方案导出为txt/csv问题求助
Fixing BoxPacking Export Error: Converting Container to Data Frame
Hey there! I’ve messed around with the BoxPacking package a bit, so let me help you solve this export issue. That error you’re seeing makes total sense—Container objects are custom S4 classes from the package, not standard data frames, so you can’t just convert them directly. Instead, you need to extract the actual box packing details first.
Step-by-Step Solution
- Extract packed box details: Use the package’s built-in
getBoxes()function to pull out all the successfully packed boxes from yourContainerobject. This returns a list ofBoxobjects, each with their position, dimensions, and other metadata. - Convert to a data frame: Each
Boxobject can be converted to a single-row data frame withas.data.frame(). We’ll uselapply()to do this for every box, thendo.call(rbind, ...)to combine them into one full data frame. - Export to CSV/TXT: Now that you have a standard data frame, you can use R’s regular export functions like
write.csv()orwrite.table().
Full Working Example
Here’s a complete code snippet to demonstrate (replace with your own container/boxes):
library(BoxPacking) # Example setup (skip if you already have your packed container) my_container <- Container(width = 20, height = 20, depth = 20) my_boxes <- list(Box(5,5,5), Box(6,6,6), Box(7,7,7)) packed_container <- pack(my_container, my_boxes) # Extract boxes and convert to data frame packed_boxes_list <- getBoxes(packed_container) packed_boxes_df <- do.call(rbind, lapply(packed_boxes_list, as.data.frame)) # Export to CSV write.csv(packed_boxes_df, "box_packing_solution.csv", row.names = FALSE) # Or export to TXT (tab-separated) write.table(packed_boxes_df, "box_packing_solution.txt", sep = "\t", row.names = FALSE)
Extra Tip
If you also need to export the unpacked boxes (the ones that didn’t fit), use getUnpackedBoxes() instead of getBoxes()—the conversion and export process works exactly the same way.
内容的提问来源于stack exchange,提问作者Rhys
相关产品推荐
相关产品推荐

