0

I learned via this post (Adding a prefix to column names) how to change the names of all the variables in a dataset at once, but I can't seem to change the name of only a subset of those variables. The dataset has 358 variables in total, and I am able to add a prefix to all of the variables, but not just a subset.

I am using the following code, but the names don't seem to be changing.

colnames(y6t1data[,75:358]) <- paste("Y6T1",colnames(y6t1data[,75:358]), sep = "_")
Benji
  • 207
  • 2
  • 9
  • You need `colnames(y6t1data)[75:358] <- ` and similarly on the RHS – akrun Nov 14 '17 at 06:37
  • Does this answer your question? [Difference between \`names(df\[1\]) <- \` and \`names(df)\[1\] <- \`](https://stackoverflow.com/questions/23427925/difference-between-namesdf1-and-namesdf1) – camille Nov 19 '19 at 15:22

1 Answers1

0

If you are using data.table framework, an intuitive way to do that is:

setnames(y6t1data, 75:358, paste("Y6T1",names(y6t1data)[75:358], sep = "_")

This syntax alows you to transform names, by regex...

For more info, pleace check:

? setnames
Emmanuel-Lin
  • 1,848
  • 1
  • 16
  • 31