繁体   English   中英

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

[英]Rename column names of a dataframe with incrementation

我有一个生成 dataframe 的脚本,其中包含多个以数字 1、2、3 命名的列 –> n

我想用以下名称重命名列:“Cluster_1”、“Cluster_2”、“Cluster_3”->“Cluster_n”(递增)。

由于我的 dataframe 中的列数可以根据我的脚本的另一部分进行相应更改,因此我希望能够拥有一种循环结构,该循环结构将 go 通过我的 dataframe 并相应地更改列。

我想做类似的事情:

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

在循环上下文之外,我通常使用此表达式来重命名列:

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

但是我很难生成此表达式的改编版本,该版本可以将字符串和变量值的串联正确地集成到我的 for 循环中。

如何调整重命名 dataframe 列的表达式以集成到我for循环中?

还是有比for循环更好的方法来做到这一点?

一个 tidyverse 解决方案: rename_with()

require(dplyr)

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

使用paste0

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

如果您真的需要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

注意: colnames()/rownames()是为 class "matrix"设计的,对于"data.frame" s,你可能想使用names()/row.names()


数据:

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

暂无
暂无

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

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