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

如何用data.table的setcolorder按另一数据框列重排数据框列

Fixing the setcolorder Error When Reordering Columns with data.table

Hey there! Let's sort out this error you're seeing with setcolorder. The problem here is pretty straightforward: the setcolorder function doesn't accept a key= argument — that's not one of its parameters.

Why You Got the Error

When you ran gf3<-setcolorder(df1, key=df2$names), you tried to pass the column order vector using a named argument that doesn't exist. setcolorder expects the new column order as its second positional argument (no need for a parameter name like key).

The Correct Implementation

First, a quick note about data.table behavior: most set* functions like setcolorder modify the data.table in-place (they change the original object directly). If you want to keep your original df1 intact, make sure to copy it first with copy().

Here's the step-by-step fix:

  1. Load the data.table package (if you haven't already)
  2. Create a copy of df1 to avoid modifying the original data
  3. Use setcolorder with just the target data.table and your desired column order vector
library(data.table)

# Example data matching your scenario
df1 <- data.table(five = 1:5, two = 6:10, three = 11:15, one = 16:20, four = 21:25)
df2 <- data.table(names = c("one", "two", "three", "four", "five"))

# Make a copy of df1 first (critical if you want to preserve the original)
gf3 <- copy(df1)

# Reorder columns directly with df2$names — no key= argument!
setcolorder(gf3, df2$names)

# Check the result
gf3

Key Notes to Remember

  • Always use copy() if you don't want to alter the original data.table — skipping this will change df1's column order permanently.
  • Double-check that every name in df2$names exists in df1 — if there's a mismatch, setcolorder will throw an error about missing columns.
  • setcolorder is designed for speed (it's optimized for data.table), so it doesn't return the modified table — that's why we modify the copied table directly.

内容的提问来源于stack exchange,提问作者Jakhongir Alidjanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:11:54