5

I am trying to alter a select few of my variable names in a data frame. How can I do this without typing each of the old names and each of the new names? I thought the code below might work but it hasn't. I am trying to append "Econ" to each of the existing names identified in the data frame.

    names(wb.misc)[3,13,14,20,22,47,61,62,64,68,73] <- 
         paste("Econ", names(wb.misc)[3,13,14,20,22,47,61,62,64,68,73], sep = "-")
Jeromy Anglim
  • 33,939
  • 30
  • 115
  • 173
DBK
  • 317
  • 3
  • 11

2 Answers2

10

You need to put c() around the indices

 names(wb.misc)[c(3,13,14,20,22,47,61,62,64,68,73)] = paste("Econ", names(wb.misc)[c(3,13,14,20,22,47,61,62,64,68,73)], sep = "-")
adibender
  • 7,288
  • 3
  • 37
  • 41
1

One way to efficiently get the variable names is to use dput(names(df)) where df is your data.frame.

For example, using the built-in dataset airquality, you can do the following

dput(names(airquality))

Which gives you:

c("Ozone", "Solar.R", "Wind", "Temp", "Month", "Day")

You can then edit to extract the columns you want without having to type them from scratch. E.g., say you want to rename the following three variables, you could use rename.vars in gdata.

vars <- c("Ozone",  "Wind", "Temp")
library(gdata)
rename.vars(airquality, from=vars, to=paste0("Econ", vars))

Using actual variable names will also generally make your code more reliable.

Jeromy Anglim
  • 33,939
  • 30
  • 115
  • 173