Achal Neupane
Achal Neupane

Reputation: 5719

change column names with same name in dataframe

I have a dataframe mydf with n number of columns with same column name say name. I want to change them to name1 name2 and name3 ..name-nth columns. How do I do that in R?

Upvotes: 5

Views: 5967

Answers (2)

mathematical.coffee
mathematical.coffee

Reputation: 56905

cols <- which(names(mydf == 'name'))
names(mydf)[cols] <- paste0('name', seq_along(cols))

The first line finds the indices of the columns with name 'name'. The second assigns new names.

Upvotes: 7

Rorschach
Rorschach

Reputation: 32416

cols <- names(dat) == "name"
names(dat)[cols] <- paste0("name", seq.int(sum(cols)))

Upvotes: 4

Related Questions