0

I looked up a lot of similar questions on Stackoverflow but I could not locate the one I am asking.

Consider a dataset:

A B C D E F G a b c d e f g

And mapping dataset to be: current desired

B H C I D J E K F L

namechangevector <- c('B', 'C', 'D', 'E', 'F')

I am using this command:

colnames(data[namechangevector]) <- as.character(mappingdata$desired[match(names(data[namechangevectors]), mappingdata$current)])

But, this doesn't work. However, this works:

colnames(data)[2:6] <- as.character(mappingdata$desired[match(names(data[namechangevectors]), mappingdata$current)])

But since, the vector can have more values and dataset can keep changing. I want to match using the vector and not the position. Please help!

Bruce Wayne
  • 471
  • 5
  • 18
  • 1
    What about: `colnames(data)[which(colnames(data) %in% namechangevector)] <- ...`? Also, it is always good to include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with your question. – Andrew Mar 01 '19 at 21:00
  • Did not work. The command makes no change to the data – Bruce Wayne Mar 01 '19 at 21:04
  • Ok, can you provide a reproducible example with your expected results? – Andrew Mar 01 '19 at 21:08
  • `names(data)[names(data) %in% namechangevector] <-new.namechangevector`. Also in your first command, try changing `colnames(data)[namechangevector] <-` instead of `colnames(data[namechangevector]) <-` , it's a very subtle difference, look at your second code for a clue – infominer Mar 01 '19 at 21:09
  • I did try colnames(data)[namechangevector], but this doesn't work either. Neither does this: `colnames(data)[which(colnames(data) %in% namechangevector)] <- as.character(mappingdata$desired[match(names(data[namechangevector]), mappingdata$current)])` – Bruce Wayne Mar 01 '19 at 21:11
  • I am working on dummy reproducible data – Bruce Wayne Mar 01 '19 at 21:12
  • Refer to this for an example. Just a few columns instead of all/. https://stackoverflow.com/questions/53714977/change-all-r-columns-names-using-a-reference-file – Bruce Wayne Mar 01 '19 at 21:22
  • https://stackoverflow.com/questions/53714977/change-all-r-columns-names-using-a-reference-file – Bruce Wayne Mar 20 '19 at 22:20

0 Answers0