Renaming Column Names in R

Viewed 241

I would like to rename my columns from my data frame which have duplicated column names where my columns are a,b and c.

 df>
 a  b  c  a  b  c
 1  6 11  1  4  4
 2  7 12  2  8  12
 3  8 13  3  7  7
 4  9 14  5  7  11
 5 10 15  44 2  13

I could change the columns name by taking out column 1:3 as df1, but is there a way to loop it if I have 1000 column names to change?

df1 <- df[,1:3]
colnames(df1) <- paste(colnames(df1), "test1" , sep = '_')
2 Answers

If you know that the same 3 column names repeat in the same order, you could just use rep here with the each option:

namenums <- rep(1:(ncol(df1)/3), each=3)
colnames(df1) <- paste0(colnames(df1), "_test", namenums)
df1

  a_test1 b_test1 c_test1 a_test2 b_test2 c_test2
1       1       6      11       1       6      11
2       2       7      12       2       7      12
3       3       8      13       3       8      13
4       4       9      14       4       9      14
5       5      10      15       5      10      15

Data:

df <- data.frame(a=c(1:5), b=c(6:10), c=c(11:15), a=c(1:5), b=c(6:10), c=c(11:15))
names(df) <- c("a", "b", "c", "a", "b", "c")

We can use make.unique

names(df) <- make.unique(names(df))
Related