簡體   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