使用data.table::melt多列融合功能时遇变量未找到错误
data.table::melt Multi-Column Reshaping It looks like the root cause of your error is a mismatch in the length of your column groups passed to the measure argument.
When using data.table::melt with measure = list(...) for multi-column reshaping, each sub-list in measure must have the exact same number of columns. This is because the function pairs columns by their position across groups—for example, p1 pairs with change1, r1, t1, idle_days1; p2 pairs with change2, r2, etc.
Looking at your code:
colA(p1-p5) has 5 columnscolB(change1-change4) andcolE(idle_days1-idle_days4) only have 4 columns eachcolC/colDhave 5 columns matchingcolA
When melt tries to process the 5th pair, it looks for change5 and idle_days5 which don't exist in your data, hence the error.
Solution 1: Pad shorter column groups with NA columns
If p5 should exist but doesn't have corresponding change/idle_days data, add those missing columns to your data first:
# Add missing columns with NA values inventory_final[, `:=`( change5 = NA_real_, # Use NA_integer_ if your change columns are integers idle_days5 = NA_integer_ )] # Update your column group vectors to include the new columns colB = paste("change", 1:5, sep = "") colE = paste("idle_days", 1:5, sep = "") # Now run melt again data <- data.table::melt( inventory_final, measure = list(colA, colB, colC, colD, colE), value.name = c("PriceNum", "PercentChange", "RentedDate", "TermDate", "IdleDays") )
Solution 2: Truncate longer column groups to match shorter ones
If p5 doesn't need to be included in the reshaped output, trim your longer column groups to match the length of the shortest ones (4 columns):
# Truncate colA, colC, colD to 4 columns colA = paste("p", 1:4, sep = "") colC = paste("r", 1:4, sep = "") colD = paste("t", 1:4, sep = "") # Run melt with matched-length column groups data <- data.table::melt( inventory_final, measure = list(colA, colB, colC, colD, colE), value.name = c("PriceNum", "PercentChange", "RentedDate", "TermDate", "IdleDays") )
Quick Validation Step
Before running melt, you can double-check that all columns exist in your data with this line:
all(c(colA, colB, colC, colD, colE) %in% names(inventory_final))
This should return TRUE if all columns are present (which you confirmed, but it's a good sanity check!).
内容的提问来源于stack exchange,提问作者Jess

