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

如何通过关联DataFrame映射实现列重命名?

Rename DataFrame Columns Using a Mapping Table in R

Got it, here's how you can rename your DataFrame columns using that mapping table in R—two approaches depending on how many columns you're dealing with:

Example Data

First, let's set up the two DataFrames you referenced:

Original Data (original)

original <- data.frame(a = c(1,2,3), b = c(4,5,6))
# Output:
#   a b
# 1 1 4
# 2 2 5
# 3 3 6

Column Mapping (new)

This table links your old column names to their new ones:

new <- data.frame(old_name = c('a','b'), new_name = c('c','d'))
# Output:
#   old_name new_name
# 1        a        c
# 2        b        d

Solution 1: Manual Rename (Great for Small Datasets)

If you only have a handful of columns, you can directly spell out each rename in dplyr::rename():

library(tidyverse)

result <- original %>% 
  rename(c = a, d = b)

# Check the final result:
result
#   c d
# 1 1 4
# 2 2 5
# 3 3 6

Solution 2: Dynamic Batch Rename (Scalable for Large Datasets)

If you've got lots of columns (or just don't want to hardcode every mapping), turn the mapping table into a named vector and use it to rename everything in one step:

# Convert the mapping table to a named vector:
# New column names become the vector's names, old names become the values
name_map <- deframe(new %>% select(new_name, old_name))

# Use this vector to batch-rename columns
result_scalable <- original %>% 
  rename(all_of(name_map))

# This gives exactly the same output as the manual method
result_scalable

Verify Your Output

You can use dput() to export the structure of all three objects to confirm everything worked as expected:

dput(list(original, new, result))

Which will output:

list(structure(list(a = c(1, 2, 3), b = c(4, 5, 6)), class = "data.frame", row.names = c(NA, 
-3L)), structure(list(old_name = c("a", "b"), new_name = c("c", 
"d")), class = "data.frame", row.names = c(NA, -2L)), structure(list(
    c = c(1, 2, 3), d = c(4, 5, 6)), class = "data.frame", row.names = c(NA, 
-3L)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:08:29