tamcle
tamcle

Reputation: 15

How to rename columns with the same name so that they're different?

I was combining columns from data tables using cbind() and some of these columns happened to have the same name but different data, which R usually catches and changes them by adding a ..1 after the initial column name, but I guess using cbind() prevented R from catching it? I want to rename the columns which I would usually do by using colnames(data)[colnames(data)=="column"] <- column..1 but because these 2 columns have the same name, I can't change one without also changing the other. How do I get around this?

Upvotes: 0

Views: 990

Answers (2)

AndS.
AndS.

Reputation: 8110

One easy way of doing this is to use the janitor package.

df <- cbind(data.frame(col1 = c(1,2)), data.frame(col1 = c(2,3))) 
df
#>   col1 col1
#> 1    1    2
#> 2    2    3

and then we use the clean_names function to tidy

janitor::clean_names(df)
#>   col1 col1_2
#> 1    1      2
#> 2    2      3

Upvotes: 2

Chelmy88
Chelmy88

Reputation: 1116

You can rename all column with :

colnames(data)<-c("col1","col2","col3", etc)

or if you know that you have exactly only two columns with the same names, you can do something like:

colnames(data)[colnames(data)=="column"] <- c("col1","col2")

Another solution is to rename the columns before applying cbind()

Upvotes: 0

Related Questions