0

I have merged several data frames and the headers lack clarity. I need to change them from 'Indicator' to 'NEWNAMES'

The data frame I created is called new_names and follows this pattern :

**NEWNAME**   **Indicator**
Housing price  Indicator1
Water Stress    WSL

the dataframe that needs changed is 'WS_MAT' and looks like this

     Country Year Indicator1 EMP.c WSL
     FR     2015  22         23   23
     USA    2019  1000       513  55

I tried

colnames(WS_MAT) <- ifelse(colnames(WS_MAT)==new_names$Indicator,new_names$NEWNAME, colnames(WS_MAT))

but I get an error message : Error in dimnames(x) <- dn : la longueur de 'dimnames' [2] n'est pas égale à l'étendue du tableau

Sorry my computer is in French, but from what I understood, it treats colnames as a function. If you have any suggestion, please let me know! thanks.

Lea7885
  • 97
  • 1
  • 9
  • Your question is answered here https://stackoverflow.com/questions/20987295/rename-multiple-columns-by-names. I would personally go with Gorka's answer, but that's just a personal preference. – R me matey Jul 02 '20 at 12:53
  • Hey @Rmematey, thank you for flagging that. I have a few issues. My table was not a data frame, whenI convert it it changes the format of my titles e.g. My title becomes My.title . I was also looking for a conditional replacement because the new_names table is not the same length as my column headers to be replaced and has empty cells. – Lea7885 Jul 02 '20 at 13:28
  • 1
    I'm not sure I understand what you mean, do you think you could create a reproducible example? – R me matey Jul 02 '20 at 13:51
  • Actually, I looked further into the answers you the link you gave and Joey's answer http://stackoverflow.com/a/36010381/4606130 solved part of my issue. My data frame WS_MAT has 235 columns. I wanted to do a conditional replacement is because name replacement sheet has empty cells. E.g. Newname Indicator Medical graduates MEDICALGRAD NA NURSEGRAD – Lea7885 Jul 02 '20 at 14:10

1 Answers1

0

thanks to your suggestions @r-me-matey and pointers to other threads http://stackoverflow.com/a/36010381/4606130, I got a solution that works for me. the data frame that needs the column name changed is FINAL (then renamed d). the data frame containing the reference column and the new names is called protocol

d<-data.frame(FINAL, check.names=FALSE)
Indicator<-data.frame(colnames(FINAL))
library(data.table)
existing <- match(protocol$'Indicator',names(d))
names(d)[na.omit(existing)] <- protocol$NEWNAME[which(!is.na(existing))]
Dharman
  • 30,962
  • 25
  • 85
  • 135
Lea7885
  • 97
  • 1
  • 9