简体   繁体   English

使用递增重命名 dataframe 的列名称

[英]Rename column names of a dataframe with incrementation

I have a script generating a dataframe with multiple columns named with numbers 1, 2, 3 –> n我有一个生成 dataframe 的脚本,其中包含多个以数字 1、2、3 命名的列 –> n

I want to rename the columns with the following names: "Cluster_1", "Cluster_2", "Cluster_3" –> "Cluster_n" (with incrementation).我想用以下名称重命名列:“Cluster_1”、“Cluster_2”、“Cluster_3”->“Cluster_n”(递增)。

As the number of columns in my dataframe can change accordingly to another part of my script, I would like to be able to have a kind of loop structure that would go through my dataframe and change columns accordingly.由于我的 dataframe 中的列数可以根据我的脚本的另一部分进行相应更改,因此我希望能够拥有一种循环结构,该循环结构将 go 通过我的 dataframe 并相应地更改列。

I would like to do something like:我想做类似的事情:

for (i in colnames(df)){
    an expression that would change the column name to a concatenation of "Cluster_" + i
}

Outside the loop context, I generally use this expression to rename a column:在循环上下文之外,我通常使用此表达式来重命名列:

names(df)[names(df) == '1'] <- 'Cluster_1'

But I struggle to produce an adapted version of this expression that would properly integrate in my for loop with a concatenation of string and variable value.但是我很难生成此表达式的改编版本,该版本可以将字符串和变量值的串联正确地集成到我的 for 循环中。

How can I adjust the expression that renames the column of the dataframe to integrate in my for loop?如何调整重命名 dataframe 列的表达式以集成到我for循环中?

Or is there a better way than a for loop to do this?还是有比for循环更好的方法来做到这一点?

A tidyverse solution: rename_with()一个 tidyverse 解决方案: rename_with()

require(dplyr)

## '~' notation can be used for formulae in this context:
df <- rename_with(df, ~ paste0("Cluster_", .))

Using paste0 .使用paste0

names(df) <- paste0('cluster_', seq_len(length(df)))

If you really need a for loop, try如果您真的需要for循环,请尝试

for (i in seq_along(names(df))) {
  names(df)[i] <- paste0('cluster_', i)
}

df
#   cluster_1 cluster_2 cluster_3 cluster_4
# 1         1         4         7        10
# 2         2         5         8        11
# 3         3         6         9        12

Note: colnames()/rownames() is designed for class "matrix" , for "data.frame" s, you might want to use names()/row.names() .注意: colnames()/rownames()是为 class "matrix"设计的,对于"data.frame" s,你可能想使用names()/row.names()


Data:数据:

df <- data.frame(matrix(1:12, 3, 4))

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

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