You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

根据名称重复表格列 | 附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" tells melt() to retain the product names as the anchor that repeats across rows
  • variable.name defines what to call the new column holding the shift labels ("9-10", "21-23")
  • value.name names 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:33:25