如何为 r 中的每三列添加相同的列名?

How to add same column name for every three column in r?

以下数据集有 12 列。 我想将第一个三列命名为 beta_0 C1,beta_1 C1,beta_2 C1,第二个三列命名为 beta_0 C2,beta_1 C2,beta_2 C2,第三个三列命名为 beta_0 C3,beta_1 C3,beta_2 C3,最后三列命名为 beta_0 C4,beta_1 C4,beta_2 C4。所以前三列名称应该是 beta

keep.beta
    1 6.009120 0.2166525 -0.008478577 6.105035 0.1345780  0.0001298016 6.091128 0.1808043 -0.0047503156 5.983053  0.18146092 -0.0041218805
    2 6.036639 0.2026568 -0.007777900 6.078765 0.1694019 -0.0031217806 6.054529 0.1762349 -0.0027424595 6.099354  0.11931962  0.0001316802
    3 5.952496 0.2157215 -0.008401910 6.035606 0.1999879 -0.0059908016 6.072109 0.1729179 -0.0005814312 6.206981  0.03777493  0.0052947380
    4 5.865918 0.2409727 -0.009400659 6.022302 0.2754867 -0.0141658120 5.826225 0.3095402 -0.0114837304 6.502510 -0.15931631  0.0202379570
    5 5.834707 0.2612805 -0.011745155 6.201962 0.2235911 -0.0111638649 5.718806 0.3864935 -0.0176355659 7.047519 -0.45893274  0.0426510068
    6 5.808203 0.2424992 -0.009300064 6.211212 0.2832388 -0.0180178390 5.547613 0.4798035 -0.0257948387 7.220851 -0.60139937  0.0534528140

感谢任何帮助。

构建碱基名称列表,然后添加序列号。

base<-c("beta_0 C", "beta_1 C", "beta_2 C")
names(df)<-paste0(rep(base, times=4), rep(1:4, each=3))

[1] "beta_0 C1" "beta_1 C1" "beta_2 C1" "beta_0 C2" "beta_1 C2" "beta_2 C2" "beta_0 C3" "beta_1 C3" "beta_2 C3"
[10] "beta_0 C4" "beta_1 C4" "beta_2 C4"

您可以为 colnames(keep.beta) 提供包含所有名称的向量,但另一种方法是像下面这样优化名称。

colnames(keep.beta) <- paste("beta_",c(0:2)," C",rep(1:4,each = 3),sep="")

粘贴命令return这个:

[1] "beta_0 C1" "beta_1 C1" "beta_2 C1" 
[4] "beta_0 C2" "beta_1 C2" "beta_2 C2" 
[7] "beta_0 C3" "beta_1 C3" "beta_2 C3"
[10] "beta_0 C4" "beta_1 C4" "beta_2 C4"