根据名称重复表格列 | 附Excel宽表示例(偏好data.table解法)
Alright, let's work through this problem—since you asked for a data.table solution first, that's what I'll lead with.
Step 1: Confirm the starting data
First, let's reuse your data.table definition to keep things consistent:
library(data.table) a <- data.table(names = c("product 1", "product 2"), "9-10" = c(1, 5), "21-23" = c(3, 2))
When printed, your initial wide-format table looks like this:
names 9-10 21-23 1: product 1 1 3 2: product 2 5 2
Step 2: Data.table solution (wide to long format)
From your description, it sounds like you want to convert this wide table into a long format where each product-machine shift pair gets its own row (meaning the names values repeat for each shift column).
The melt() function in data.table is perfect for this task:
# Convert wide table to long format a_long <- melt(a, id.vars = "names", # Keep this column as the repeating identifier variable.name = "machine_shift", # Name for the new shift label column value.name = "capacity") # Name for the capacity values column
Result of the code
Running the above will give you this cleaned long-format table:
names machine_shift capacity 1: product 1 9-10 1 2: product 2 9-10 5 3: product 1 21-23 3 4: product 2 21-23 2
Quick code breakdown
id.vars = "names"tellsmelt()to retain the product names as the anchor that repeats across rowsvariable.namedefines what to call the new column holding the shift labels ("9-10", "21-23")value.namenames the column that stores the actual capacity numbers
Alternative: Tidyverse solution
If you prefer using tidyverse tools, here's an equivalent approach with dplyr and tidyr:
library(tidyverse) a_long_tidy <- a %>% pivot_longer(cols = -names, names_to = "machine_shift", values_to = "capacity")
This produces the exact same output as the data.table version—just a different syntax for your preferred workflow.
内容的提问来源于stack exchange,提问作者PavoDive

