简体   繁体   English

如何重命名R中的多个列?

[英]How to rename multiple Columns in R?

My goal is to get a concise way to rename multiple columns in a data frame.我的目标是获得一种简洁的方法来重命名数据框中的多个列。 Let's consider a small data frame df as below:让我们考虑一个小的数据框df,如下所示:

df <- data.frame(a=1, b=2, c=3)
df 

Let's say we want to change the names from a, b, and c to Y, W, and Z respectively.假设我们要将名称从 a、b 和 c 分别更改为 Y、W 和 Z。 Defining a character vector containing old names and new names.定义包含旧名称和新名称的字符向量。

df names <- c(Y = "a", Z ="b", E = "c")

I would use this to rename the columns,我会用它来重命名列,

rename(df, !!!names)
df

suggestions?建议?

One more !再来一张! :

df <- data.frame(a=1, b=2, c=3)
df_names <- c(Y = "a", Z ="b", E = "c")
library(dplyr)
df %>% rename(!!!df_names)
##  Y Z E
##1 1 2 3

A non-tidy way might be through match :一种不整洁的方式可能是通过match

names(df) <- names(df_names)[match(names(df), df_names)]
df
##  Y Z E
##1 1 2 3

You could try:你可以试试:

sample(LETTERS[which(LETTERS %in% names(df) == FALSE)], size= length(names(df)), replace = FALSE)
[1] "S" "D" "N"

Here, you don't really care what the new names are as you're using sample.在这里,您并不真正关心新名称是什么,因为您正在使用示例。 Otherwise a straight forward names(df) < c('name1', 'name2'...否则,直接的names(df) < c('name1', 'name2'...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM