rename multiple columns at once by keeping some property of the column name

I have a dataset

sales <- data.frame(
  Item = c("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o"),
  sale1 = c(0,1,1,1,1,2,0,0,0,0,0,1,2,1,2),
  sale2 = c(0,0,NA,0,1,2,1,1,0,0,1,1,1,2,1),
  sale3 = c(0,2,1,1,2,1,2,0,0,0,0,0,2,1,2),
  sale4 = c(0,1,1,1,1,1,NA,0,0,0,2,1,2,1,2),
  sale5 = c(0,1,1,1,1,1,1,1,2,2,1,2,1,2,1),
  sale6 = c(0,1,2,2,2,2,1,2,1,2,0,1,0,1,2),
  sale7= c(0,2,1,2,1,1,0,0,1,2,0,1,2,0,1),
  sale8 = c(0,0,0,0,0,0,1,2,1,0,0,1,2,1,NA),
  sale9 = c(0,1,2,0,0,0,0,0,1,2,1,0,1,2,1),
  sale10 = c(1,0,1,2,NA,1,2,1,0,1,2,0,1,2,0),
  sale11 = c(0,1,2,1,1,1,0,0,1,2,0,NA,1,2,1),
  sale12= c(0,1,2,NA,1,2,0,0,0,0,1,2,1,0,0)
)

I am looking to change the name of the columns sale1 : sale12 at once where my new column names will be named as newname1 : newname12 such that sale1 = newname1, sale2 = newname2 and on. The numeric number part in the col name (1,2,3...) needs to be preserved for identification purpose.

Is there an easy way to do this than having to do it one column at a time? (imagine there are 400 columns to work on this at once). Thank you.

Here is one solution.

sales <- data.frame(
  Item = c("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o"),
  sale1 = c(0,1,1,1,1,2,0,0,0,0,0,1,2,1,2),
  sale2 = c(0,0,NA,0,1,2,1,1,0,0,1,1,1,2,1),
  sale3 = c(0,2,1,1,2,1,2,0,0,0,0,0,2,1,2),
  sale4 = c(0,1,1,1,1,1,NA,0,0,0,2,1,2,1,2),
  sale5 = c(0,1,1,1,1,1,1,1,2,2,1,2,1,2,1),
  sale6 = c(0,1,2,2,2,2,1,2,1,2,0,1,0,1,2),
  sale7= c(0,2,1,2,1,1,0,0,1,2,0,1,2,0,1),
  sale8 = c(0,0,0,0,0,0,1,2,1,0,0,1,2,1,NA),
  sale9 = c(0,1,2,0,0,0,0,0,1,2,1,0,1,2,1),
  sale10 = c(1,0,1,2,NA,1,2,1,0,1,2,0,1,2,0),
  sale11 = c(0,1,2,1,1,1,0,0,1,2,0,NA,1,2,1),
  sale12= c(0,1,2,NA,1,2,0,0,0,0,1,2,1,0,0)
)
colnames(sales) <- sub(pattern = "sale",replacement = "newname",colnames(sales))
colnames(sales)
#>  [1] "Item"      "newname1"  "newname2"  "newname3"  "newname4"  "newname5" 
#>  [7] "newname6"  "newname7"  "newname8"  "newname9"  "newname10" "newname11"
#> [13] "newname12"

Created on 2021-10-25 by the reprex package (v2.0.1)

1 Like

Thank you. This worked.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.