hanzgs
hanzgs

Reputation: 1616

Replace Column Names in R

How to replace the column names in r, for example say columns A,B,C,D, I wish to change all as A_id, B_id, C_id, D_id, so all column names will have "_id" at the end.

Using str_replace_all we can find the specific string and replace, but I don't know how to change at the end

df %>% str_replace_all( '_', '_id')

Expecting in a single sort of code

Upvotes: 1

Views: 1168

Answers (1)

morgan121
morgan121

Reputation: 2253

You can use the names or colnames function like this:

names(df) <- paste0(names(df), "_id")

Or you can combine this with gsub to only replace specific things, e.g if you want to replace any names in the iris dataset to use space not full stop you can write:

df <- head(iris)
names(df) <- gsub("[.]", " ", names(df))

Upvotes: 2

Related Questions