MNU
MNU

Reputation: 764

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

The following data set has 12 columns. I would like to namebeta_0 C1,beta_1 C1,beta_2 C1 for the first three-column and beta_0 C2,beta_1 C2,beta_2 C2 for second three column, beta_0 C3,beta_1 C3,beta_2 C3 for the third three column and beta_0 C4,beta_1 C4,beta_2 C4 for the last three column. So first three column names should be 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

Any help is appreciated.

Upvotes: 0

Views: 59

Answers (2)

Gowachin
Gowachin

Reputation: 1270

You can provide a vector to colnames(keep.beta) with all the names, but another way is to automise the names like bellow.

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

The paste command return this :

[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"

Upvotes: 2

Dave2e
Dave2e

Reputation: 24079

Build the base name list and then add the sequence number.

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"

Upvotes: 1

Related Questions